美文网首页iOS开发
UITextView点击蓝色字体跳转

UITextView点击蓝色字体跳转

作者: 一笔春秋 | 来源:发表于2017-06-13 14:31 被阅读39次

    1、初始化

    UITextView *_commentView = [[UITextView alloc] init]; 

    _commentView.userInteractionEnabled = NO;

    2、设置属性

    NSString* comment = @"测试4006";

    NSRange telRange = [comment rangeOfString:@"4006"];

    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc]initWithString:comment];

    NSMutableParagraphStyle* paragraph = [[NSMutableParagraphStyle alloc] init];

    [paragraph setLineSpacing:4];//设置行间距

    [paragraph setParagraphSpacing:10];//设置段落间距

    [paragraph setAlignment:NSTextAlignmentLeft];//设置对齐方式

    [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, comment.length)];

    [attrStr addAttribute:NSForegroundColorAttributeName value:COLOR_HEX(@"7bb0ee") range:telRange];

    [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, comment.length)];

    _commentView.attributedText = attrStr;

    NSArray* selectionRects = [_commentView selectionRectsForRange:telRange];

    if (selectionRects.count>0) {

        UITextSelectionRect *selectionRect = [selectionRects objectAtIndex:0];

        telTextFrame = selectionRect.rect;

    }

    3、添加点击事件

    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];

    [_commentView addGestureRecognizer:tap];

    -(void)tapAction:(UITapGestureRecognizer*)tap

    {

         CGPoint point = [tap locationInView:_commentView];

        if(!CGRectEqualToRect(telTextFrame, CGRectZero))

        {

            if (CGRectContainsPoint(telTextFrame, point)) {

                NSLog(@"点击400");

            }

        }

    }

    相关文章

      网友评论

        本文标题:UITextView点击蓝色字体跳转

        本文链接:https://www.haomeiwen.com/subject/twmdqxtx.html