当前位置: 首页 > 工具软件 > YYText > 使用案例 >

YYText识别链接和点击事件

贺善
2023-12-01

在使用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;
 类似资料: