iOS UITextView 设置 NSLinkAttributeName 属性,点击链接跳转

@interface ViewController ()<UITextViewDelegate>


- (void)viewDidLoad
{
    [super viewDidLoad];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"www.google.com"];
    NSDictionary *linkDic = @{ NSLinkAttributeName : [NSURL URLWithString:@"http://www.google.com"] };
    [str setAttributes:linkDic range:[[str string] rangeOfString:@"www.google.com"]];
    _textView.attributedText = str;
}


- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    NSLog(@"=============%@",URL);
    return YES;
}


需要注意的是 将上述代码 需做如下调整 我们需要的是 点击跳转 而不是点击编辑 所以需要关闭编辑属性
如下:

在 IB 中设置以下 > 实用程序 > 属性检查器。值得注意的是,UITextView不能是可编辑,启用链接。

UITextView Settings

你也可以做同样的代码:

_textView.editable = NO;
_textView.dataDetectorTypes = UIDataDetectorTypeLink;
 
原文地址:https://www.cnblogs.com/sunfuyou/p/8603428.html