iOS中求出label中文字的行數和每一行的內容


今天遇到一個需求,需要計算label中文字的行數。想了好久也沒想到好的解決方法,就在網上找了下。結果發現一篇文章是講這個的。這部分代碼不但能夠求出一個label中文字行數,更厲害的是能夠求出每一行的內容是什么; 代碼如下。

#import <CoreText/CoreText.h>

- (NSArray *)getLinesArrayOfStringInLabel:(UILabel *)label{ NSString *text = [label text]; UIFont *font = [label font]; CGRect rect = [label frame]; CTFontRef myFont = CTFontCreateWithName(( 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)]; CFRelease(myFont); CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( 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 = ( 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]; CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0])); CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0])); //NSLog(@"''''''''''''''''''%@",lineString); [linesArray addObject:lineString]; } CGPathRelease(path); CFRelease( frame ); CFRelease(frameSetter); return (NSArray *)linesArray; }

 

文章參照 鏈接
函數返回的數組的count 即為label中文字行數 ;數組中元素即為某行內容。

轉載請注明出處:
原文地址:http://mingxianwei.github.io/2016/05/27/iOS中求出label中文字的行數和每一行的內容
作者:小土豆

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM