ios 获取Text行数和每行显示的内容

该方法主要使用了CoreText中的内容,了解更多CoreText的内容请看CoreText系列

下面是具体代码

- (NSArray *)getLinesArrayOfStringInLabel:(NSString *)string font:(UIFont *)font andLableWidth:(CGFloat)lableWidth{
    
    CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:string];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)myFont range:NSMakeRange(0, attStr.length)];
    CFRelease(myFont);
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,lableWidth,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    for (id line in lines) {
        CTLineRef lineRef = (__bridge  CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        NSString *lineString = [string substringWithRange:range];
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));
        [linesArray addObject:lineString];
    }
    
    CGPathRelease(path);
    CFRelease( frame );
    CFRelease(frameSetter);
    return (NSArray *)linesArray;
}
* 返回结果即为包含每行文字的数组,行数即为count数
* 该方法主要是预先的计算出文本在UIlable等控件中的显示情况,从而进行一些其它的后续操作。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,282评论 25 709
  • 有没有那么一段时间­ 你等着玫瑰花开 有没有那么一段时间­ 我把玫瑰捧在身后­ 画面被淋了雨­ 腐朽­ 隆重的沉默...
    韩马小执阅读 1,293评论 0 0
  • 从《解忧杂货店》到《白夜行》再到这一本《神探伽利略》,已被东野写作手法所吸引的我,早已将他的其余作品也列入了未读书...
    北渔说阅读 4,850评论 2 5
  • 请先给自己设定一个目标,奋斗的目标。不需要定“五年计划”这样的宏大目标。然后你可以网上,书上,论坛上找相关的攻略—...
    铎萌龙阅读 1,371评论 0 0
  • 新建curl-format.txt 使用 命令行显示如下: doc How do I measure reques...
    go4it阅读 4,916评论 0 0