YYText识别链接和点击事件

在使用YYLabel时有个比较麻烦的事情,就是YYLabel无法自动识别链接。因此我写了一个正则表达式来解决这个问题。

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"这里传入富文本"];;
// 匹配条件
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSError *error = NULL;
    // 根据匹配条件,创建了一个正则表达式
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error];
    
    if (!regex) {
        NSLog(@"正则创建失败error!= %@", [error localizedDescription]);
    } else {
        NSArray *allMatches = [regex matchesInString:attrStr.string options:NSMatchingReportCompletion range:NSMakeRange(0, attrStr.string.length)];
        for (NSTextCheckingResult *match in allMatches) {
            NSString *substrinsgForMatch2 = [attrStr.string substringWithRange:match.range];
            NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:substrinsgForMatch2];
            // 利用YYText设置一些文本属性
            one.yy_font = [UIFont systemFontOfSize:self.viewSetting.companyLabelFontSize];
            one.yy_underlineStyle = NSUnderlineStyleSingle;
            one.yy_color = ThemeColor;
            YYTextBorder *border = [YYTextBorder new];
            border.cornerRadius = 3;
            border.insets = UIEdgeInsetsMake(-2, -1, -2, -1);
            //设定颜色则点击的时候,点击链接的时候链接颜色不会变
            // border.fillColor = [UIColor greenColor];
            YYTextHighlight *highlight = [YYTextHighlight new];
            [highlight setBorder:border];
            [highlight setColor:[UIColor redColor]];
            [one yy_setTextHighlight:highlight range:one.yy_rangeOfAll];
            // 根据range替换字符串
            [attrStr replaceCharactersInRange:match.range withAttributedString:one];
        }
    }
    yyLabel.attributedText = attrStr;
    //  获得YYLabel的布局信息
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kScreen_Width-10*2, MAXFLOAT)];
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:attrStr];
    yyLabel.textLayout = textLayout;
    WEAK_SELF
    yyLabel.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
        NSLog(@"点击链接%@",[text.string substringWithRange:range]);
    };
    CGFloat yyLabelHeight = textLayout.textBoundingSize.height;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,613评论 0 11
  • 彩排完,天已黑
    刘凯书法阅读 4,277评论 1 3
  • 表情是什么,我认为表情就是表现出来的情绪。表情可以传达很多信息。高兴了当然就笑了,难过就哭了。两者是相互影响密不可...
    Persistenc_6aea阅读 126,075评论 2 7