iOS 獲取label每行顯示內(nèi)容數(shù)組及行數(shù)

開發(fā)時,經(jīng)常會需要用到label行數(shù)來做某些操作,如下方法,給label添加分類方法,可以獲得一個該label當前顯示的每行內(nèi)容的數(shù)組,如果需要行數(shù),那么直接去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;

}

文章參照鏈接

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容