美文网首页&iOS
获取UILabel每一行的文字内容

获取UILabel每一行的文字内容

作者: 我是不是叫没烦恼 | 来源:发表于2017-07-22 16:38 被阅读68次

    获取UILabel每一行的文字内容

    需要引入CoreText框架

    #import <CoreText/CoreText.h>
    

    具体实现如下,返回一个数组,存放每一行的问题本内容,根据Label的尺寸获取

    - (NSArray *)getSeparatedLinesFromLabel:(UILabel *)label {
        NSString *text = [label text];
        UIFont   *font = [label font];
        CGRect    rect = [label bounds];
        
        CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
        [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
        
        CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
        
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,MAXFLOAT));
        
        CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
        
        NSArray *lines = (__bridge 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 = [text substringWithRange:range];
            [linesArray addObject:lineString];
        }
        return (NSArray *)linesArray;
    }
    

    相关文章

      网友评论

        本文标题:获取UILabel每一行的文字内容

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