美文网首页
iOS 获取UILabel每行的字符串

iOS 获取UILabel每行的字符串

作者: sergeant | 来源:发表于2019-07-10 09:34 被阅读0次
    - (NSArray *)linesAtWidth:(CGFloat)width {
        if (self.text == nil) {
            return nil;
        }
        
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:self.text];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
        
        CTFontRef myFont = CTFontCreateWithName((CFStringRef)([self.font fontName]), [self.font pointSize], NULL);
        [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, width, CGFLOAT_MAX));
        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 = [self.text substringWithRange:range];
            [linesArray addObject:lineString];
        }
        CGPathRelease(path);
        CFRelease(frame);
        CFRelease(frameSetter);
        return linesArray;
    }
    

    相关文章

      网友评论

          本文标题:iOS 获取UILabel每行的字符串

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