美文网首页
CoreText - 获取UILabel 每行文字

CoreText - 获取UILabel 每行文字

作者: 似奔跑的野马 | 来源:发表于2018-05-02 18:18 被阅读0次

开发中,pm要求显示指定行文字,如何做?
1.对于使用UILabel来说,可以指定numberOfLines 来设置对应的行数,通过sizeToFit计算高度很方便。(注意:sizeToFit需要指定宽度)。

大多数情况下,解决了。问题来了,对于超过的行数,默认会显示....
pm不要后缀,你不能发狂~
2.解决方法也比较简单,使用CoreText 获取对应的文字,获取text可以显示多少行,以及每行有什么文字非常方便。

    NSMutableAttributedString *attributeText = [[NSMutableAttributedString alloc] initWithString:@"需要输入的文字"];

//创建frameSetter,是CTFrameRef的一个工厂方法
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributeText);
    CGMutablePathRef path = CGPathCreateMutable();
  //指定每行的宽度,此处100
    CGPathAddRect(path, NULL, CGRectMake(0, 0, 100, MAXFLOAT));
    CTFrameRef frameRef = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, attributeText.length), path, NULL);
    CFArrayRef lines = CTFrameGetLines(frameRef);
    CFIndex lineCount = CFArrayGetCount(lines);

 NSAttributedString *trimAttribute = nil;
    for(CFIndex i;i<lineCount;i++) {
      CTLineRef line = CFArrayGetValueAtIndex(lines, i);
       CFRange lineRange = CTLineGetStringRange(line);
       NSRange trimRange = NSMakeRange(0, lineRange.location + lineRange.length);
      //获取你需要的文字
        trimAttribute = [attributeText attributedSubstringFromRange:trimRange];
        }
       
    }
    
    if(frameSetter) {
        CFRelease(frameSetter);
    }
    if(frameRef) {
        CFRelease(frameRef);
    }
    CGPathRelease(path);

如果需要你也可以默认加上你想加的文字。

相关文章

网友评论

      本文标题:CoreText - 获取UILabel 每行文字

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