开发时,经常会需要用到label行数来做某些操作,如下方法,给label添加分类方法,可以获得一个该label当前显示的每行内容的数组,如果需要行数,那么直接去array的count就可以了。
-(NSArray*)getSeparatedLinesFromLabel {
NSString *text = [self text];
UIFont *font = [self font];
CGRect rect = [self 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 (NSArray*)linesArray;
}
文章参照链接