#import "firstVC.h"
#import "secondVC.h"
#import "userlist.h"
@interface firstVC ()<UITextViewDelegate>
@end
@implementation firstVC
{
NSMutableAttributedString *_attributedString;
NSArray * _dataArr;
}
- (void)viewDidLoad {
[superviewDidLoad];
// 给定一个用户列表
_dataArr =@[@"nonono",@"abc"];
}
-(void)createTextView{
UITextView * TView = [[UITextViewalloc]initWithFrame:CGRectMake(100,100, 200,100)];
TView.backgroundColor = [UIColorlightGrayColor];
TView.editable =NO;
//创建富文本
_attributedString = [[NSMutableAttributedStringalloc] initWithString:self.textviewCS.text];
for (NSString * resstrin _dataArr) {
//遍历是否存在相同字符串
if ([self.textviewCS.textrangeOfString:resstr].location!=NSNotFound) {
// 发现相同的关键字
NSString * usernameCS = resstr;
NSString * totalname = [NSStringstringWithFormat:@"@%@",usernameCS];
//添加链接的方式
[_attributedStringaddAttribute:NSLinkAttributeName
value:[NSString stringWithFormat:@"username://%@",usernameCS]
range:[[_attributedStringstring] rangeOfString:[NSStringstringWithFormat:@"%@",totalname]]];
// 设置点击时的样式
NSDictionary *linkAttributes =@{NSForegroundColorAttributeName: [UIColorgreenColor],NSUnderlineColorAttributeName: [UIColorlightGrayColor],NSUnderlineStyleAttributeName:@(NSUnderlinePatternSolid)};
// 添加链接文字
TView.linkTextAttributes = linkAttributes;
}
}
TView.attributedText =_attributedString;
TView.delegate =self;
[self.viewaddSubview:TView];
}
//点击的回调
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URLscheme] isEqualToString:@"username"]) {
// 自定义的点击文字
NSString *username = [URLhost];
NSLog(@"%@",username);
secondVC * VC = [[secondVCalloc]init];
[self.navigationControllerpushViewController:VC animated:YES];
VC.title= username;
returnNO;
}
returnYES;
}
//发布
- (IBAction)push:(UIButton *)sender {
[selfcreateTextView];
}
//跳转用户列表
- (IBAction)jumpUser:(UIButton *)sender {
userlist * userVC = [[userlistalloc]init];
[self.navigationControllerpushViewController:userVC animated:YES];
userVC.dataArr=_dataArr;
}
@end