iOS开发笔记-24:文字中添加链接

2017-03-17  本文已影响13人  原味蛋炒饭

文字中添加链接

使用富文本来添加链接

屏幕快照 2017-03-17 下午4.53.33.png
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(14, 220, SCREEN_WIDTH -24, 100)];
    _textView.backgroundColor = [UIColor clearColor];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"手机收不到验证码怎么办?\n\n1.检查垃圾短信,在设置中,将发件人设置为白名单\n2.一个账号一天最多可发送3次\n3.若手机已停用,请联系客服处理拨打客服电话"];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:
     NSMakeRange(0,12)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:
     NSMakeRange(12,attributedString.length -12)];
    
    [attributedString addAttribute:NSFontAttributeName value:FONT_OF_14 range:
     NSMakeRange(0,12)];
    [attributedString addAttribute:NSFontAttributeName value:FONT_OF_12 range:
     NSMakeRange(12,attributedString.length -12)];
    
    
    [attributedString addAttribute:NSLinkAttributeName
                             value:[NSString stringWithFormat:@"tel:%@",_kServicePhone]
                             range:[[attributedString string] rangeOfString:@"拨打客服电话"]];
    
    
    NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor],
                                     NSUnderlineColorAttributeName: [UIColor lightGrayColor],
                                     NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
    //添加链接
    _textView.linkTextAttributes = linkAttributes;
    _textView.attributedText = attributedString;
//    _textView.delegate = self;
    _textView.editable = NO;   // 非编辑状态下才可以点击Url

代理方法处理点击事件

//这里可以对点击事件进行操作
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([[URL scheme] isEqualToString:@"www"]) {
//        NSString *urlhost = [URL host];
        return NO;
    }
    return YES;
}
上一篇下一篇

猜你喜欢

热点阅读