iOS 一个灰常牛逼的 Label

4,832 阅读3分钟
原文链接: www.jianshu.com

一个灰常牛逼的label可响应部分文字的点击事件,常用于聊天微博等页面。类似微博的自动高亮label,包括url、@..、[..] #..#等都可以自动高亮,并且支持点击(响应部分文字的点击事件)、点击高亮。
git连接


1130.gif

换行时高亮

实现方法

  • 显示高亮主要是正则表达式的运用
  • 点击方法为touchBegan
  • 点击判定为coreText的运用。

主要实现过程

构建方法


构建方法

属性


Paste_Image.png


代码

    NSMutableAttributedString *maString = [self highlightText:string];
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)maString);
    [self drawFramesetter:framesetter attributedString:string textRange:CFRangeMake(0, string.length) inRect:CGRectMake(0, 5, self.frame.size.width, self.frame.size.height) context:nil];
    self.attributedText = maString;

CTFramesetterRef为coreText里边布局的几个属性之一。关于coreText用法不再多说。

highlightText方法

NSString* string = coloredString.string;
    NSRange range = NSMakeRange(0,[string length]);
    for(NSString* expression in self.ruleArray) {
        NSArray* matches = [[NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionDotMatchesLineSeparators error:nil] matchesInString:string options:0 range:range];
        for(NSTextCheckingResult* match in matches) {

            self.highRangeDic[NSStringFromRange(match.range)] = @1;
            if (currentRange.location != -1 && currentRange.location >= match.range.location && currentRange.length + currentRange.location <= match.range.length + match.range.location)
            {
                 [coloredString addAttribute:NSForegroundColorAttributeName value:self.w_selectedColor range:match.range];
                self.selectedStr = [coloredString attributedSubstringFromRange:match.range].string;
            }
            else
            {
                 [coloredString addAttribute:NSForegroundColorAttributeName value:self.w_highColor range:match.range];
            }
        }
    }
    if (self.w_range.location != NSNotFound)
    {
        self.highRangeDic[NSStringFromRange(self.w_range)] = @1;
        if (currentRange.location != -1 && currentRange.location >= self.w_range.location && currentRange.length + currentRange.location <= self.w_range.length + self.w_range.location)
        {
            [coloredString addAttribute:NSForegroundColorAttributeName value:self.w_selectedColor range:self.w_range];
            self.selectedStr = [coloredString attributedSubstringFromRange:self.w_range].string;
        }
        else
        {
            [coloredString addAttribute:NSForegroundColorAttributeName value:self.w_highColor range:self.w_range];
        }
    }
    return coloredString;

遍历存放正则表达式的数组,判断字符串是否有符合规则的子字符串,符合规则就设置高亮,上边的if..else 则是判断当前range下的字符串是否应该显示高亮。highRangeDic存放应该显示高亮的字符串的range。以便存取高亮显示的字符串的frame。 下面的if ,手动设置高亮的range会走的方法。

drawFramesetter: attributedString: textRange: inRect: context方法
由于这个方法代码太长,只贴出与本项目相关代码。

     if ((!isHighLighted&&self.superview!=nil)) {
            CFArrayRef runs = CTLineGetGlyphRuns(line);
            for (int j = 0; j < CFArrayGetCount(runs); j++) {
                CGFloat runAscent;
                CGFloat runDescent;
                CTRunRef run = CFArrayGetValueAtIndex(runs, j);
                if (highDic!=nil) {
                    CFRange range = CTRunGetStringRange(run);
                    CGRect runRect;
                    runRect.size.width = CTRunGetTypographicBounds(run, CFRangeMake(0,0), &runAscent, &runDescent, NULL);
                    float offset = CTLineGetOffsetForStringIndex(line, range.location, NULL);
                    float height = runAscent;
                    float w_y = (self.frame.size.height - numberOfLines * height - (numberOfLines - 1) * runDescent) / 2.0 + lineIndex * (height + runDescent);
                    runRect=CGRectMake(lineOrigin.x + offset, w_y, runRect.size.width, height);
                    NSRange nRange = NSMakeRange(range.location, range.length);
                    for (NSString *key in self.highRangeDic.allKeys)
                    {
                        NSRange oRange = NSRangeFromString(key);
                        if (nRange.location >= oRange.location && nRange.length + nRange.location <= oRange.location + oRange.length) {
                            [highDic setValue:[NSValue valueWithCGRect:runRect] forKey:NSStringFromRange(nRange)];
                        }
                    }
                }
            }
        }

highDic存放高亮显示的字符串的frame,键值为range。第一个for循环为遍历每一行的CTRun(coreText的类)。
numberOfLine为行数,lineIndex为当前字符串在第几行。
第二个for循环遍历当前高亮的字典,如果range为应该高亮显示的range,则添加highDic中。

touchBegan方法

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    CGPoint location = [[touches anyObject] locationInView:self];
    for (NSString *key in highDic.allKeys)
    {
        CGRect frame = [highDic[key] CGRectValue];
        if (CGRectContainsPoint(frame, location))
        {
            NSRange range = NSRangeFromString(key);
            range = NSMakeRange(range.location, range.length - 1);
            currentRange = range;
            [self showHighLightedWord];
        }
    }
}

遍历存放frame的字典,如果包含当前点击的坐标,则显示高亮。

解释一下换行时,另一行的字符串同时显示点击高亮


换行时高亮


在获取高亮显示坐标时,coreText会把换行的字符串分成两个CTRun,把两个的CTRun的坐标都保存下来,在保存高亮颜色的dic中,这两个CTRun的range,都被包括在了一个键中。

if (currentRange.location != -1 && currentRange.location >= match.range.location && currentRange.length + currentRange.location <= match.range.length + match.range.location)

currentRange为点击时从highDic获取到的
git连接