IOS - UITextView文字链接 NSLinkAttri

2020-02-01  本文已影响0人  Th丶小伟

IOS 原生需要在文字中添加超文本连接
使用UITextView NSAttributedString


NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:textView.text];
[attributedString addAttribute:NSLinkAttributeName
                                value:@"privacyProtocol://"
                                range:[[attributedString string] rangeOfString:@"《隐私条款》"]];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:[[attributedString string] rangeOfString:@"《隐私条款》"]];
textView.attributedText = attributedString;
textView.delegate = self;

-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction{
    if ([[URL scheme] isEqualToString:@"privacyProtocol"]) {

        //点击跳转代码
        return NO;
    }
    return YES;
}
WX20200201-213259@2x.png

UI要求超链接文字换别的颜色。
在textView 添加另一个属性 即可

textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithRed:135/255.0 green:135/255.0 blue:135/255.0 alpha:1]}; 
WX20200201-214229@2x.png
上一篇 下一篇

猜你喜欢

热点阅读