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

來源:互聯網
上載者:User

標籤:attr   lock   bst   com   nsa   tts   hint   substr   解決方案   

今天遇到一個需求,需要計算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中文字的行數和每一行的內容
小馬鈴薯

 

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.