将封装好的文件拖到项目中,导入头文件,调用就可以了.如图
类文件主要方法:
/**
UITextView文字超链接
@param allStr 整个字符串
@param changeStr 需要更改为超链接的部分字符
@param changeStrColor 超链接字符颜色
@param style 超链接字符的样式
@return 返回的字符串
*/
+(NSMutableAttributedString *)AllString:(NSString *)allStr ChangeString:(NSString *)changeStr ChangeStrColor:(UIColor *)changeStrColor StrStyle:(NSInteger)style {
NSString *str = [NSString stringWithFormat:@"%@", allStr];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str]; // assume string exists
NSRange urlRange = [str rangeOfString:changeStr];
[string addAttribute:NSLinkAttributeName
value:changeStr
range:urlRange];
[string addAttribute:NSForegroundColorAttributeName
value:changeStrColor
range:urlRange];
[string addAttribute:NSUnderlineStyleAttributeName
value:@(style)
range:urlRange];
[string endEditing];
return string;
}
在UITextView需要实现的地方调用,如图
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITextView * textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 200, 200, 200)];
textView.backgroundColor =[UIColor whiteColor];
//实现类方法
textView.attributedText = [ZTextViewHyperLink AllString:@"这里的天气很好,我要到百度上面去买个面膜" ChangeString:@"百度" ChangeStrColor:[UIColor blueColor] StrStyle:NSUnderlineStyleNone ];
textView.dataDetectorTypes = UIDataDetectorTypeLink;
[self.view addSubview:textView];
textView.delegate = self;
[textView setSelectable: YES];
//非编辑状态下,才能允许跳转
[textView setEditable:NO];
}
/**
代理方法
*/
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
//要打开的超链接
NSString *urlStr= @"http://www.hao123.com";
//iOS10,打开跳转链接新方法
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:^(BOOL success) {
}];
return YES;
}