美文网首页
UILabel获取每行的文本,英文略有误差

UILabel获取每行的文本,英文略有误差

作者: 狗狗臭鸡蛋 | 来源:发表于2018-06-29 14:19 被阅读13次

    需要使用 #import <CoreText/CoreText.h>

    
    - (NSArray *)getSeparatedLinesFromLabel:(UILabel *)label {
        NSString *text = [label text];
        UIFont   *font = [label font];
        CGRect    rect = [label frame];
        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,100000));
        
        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 linesArray;
    }
    

    相关文章

      网友评论

          本文标题:UILabel获取每行的文本,英文略有误差

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