有时候我们需要实现一行文中中某些文字带有点击的功能,大多数情况下会采用label和button结合实现或者第三方富文本label,其实用textView添加链接实现起来非常方便。
实现如下效果:
img
需要设置得文字

NSString *text =@"我同意《XX在线服务协议》及《XX在线用户信息及隐私保护规则》";
NSMutableAttributedString *MAttributedString = [[NSMutableAttributedString alloc] initWithString:text];
//《XX在线服务协议》
NSRange range1 = NSMakeRange(3, 10);
[MAttributedString addAttributes:@{NSLinkAttributeName:[NSURL URLWithString:@"string1://"] } range:range1];
//《XX在线用户信息及隐私保护规则》
NSRange range2 = NSMakeRange(14, 17);
[MAttributedString addAttributes:@{NSLinkAttributeName:[NSURL URLWithString:@"string2://"]}range:range2];
[MAttributedString endEditing];

textView的设置

UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20,100, SCREEN_WIDTH - 20,50)];
textView.font = [UIFont systemFontOfSize:20];
textView.scrollEnabled = NO;
textView.textContainerInset = UIEdgeInsetsMake(0, 0,2,0);
textView.text = text;
textView.textColor = [UIColor blackColor];
//必须设为NO不然不能响应点击事件
textView.editable = NO;
//设置链接的属性 设置那一段颜色
NSDictionary *linkAttributes =@{
NSForegroundColorAttributeName:[UIColor redColor]};
textView.linkTextAttributes = linkAttributes;
/** 设置自动检测类型为链接网址. */
textView.dataDetectorTypes = UIDataDetectorTypeAll;
textView.delegate = self;
textView.attributedText = MAttributedString;
[self.view addSubview:textView];

那两段文字的点击事件,在UItextView Delegate中实现

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
// 在代理方法回调的时候,如果没有“://”的话,在[URL scheme]方法里取不到特定的值,一句话://前面的才是最重要的标识符
if ([[URL scheme] rangeOfString:@"string1"].location != NSNotFound) {
NSLog(@"点击《XX在线服务协议》");
return NO;
}
else if ([[URL scheme] rangeOfString:@"string2"].location != NSNotFound){
NSLog(@"点击《XX在线用户信息及隐私保护规则》");
return NO;
}
return YES;
}