Today, when you encounter a requirement, you need to calculate the number of lines of text in the label. Thought for a long time also did not think of a good solution, on the Internet to find the next. It turns out that one article is about this. This part of the code can not only find a label in the number of lines of text, but also the ability to find out what each line of content, the code is as follows.
#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: (__bridgeID) MyFont Range:Nsmakerange (0, Attstr.length)];Cfrelease (MyFont);Ctframesetterref Framesetter =Ctframesettercreatewithattributedstring ((CFATTRIBUTEDSTRINGREF) attstr);Cgmutablepathref Path =Cgpathcreatemutable ();Cgpathaddrect (Path,NullCGRectMake (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 LineIn lines) {Ctlineref Lineref = (__bridgeCTLINEREF) 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 (CFTypeRef) ([ Span class= "hljs-built_in" >nsnumber numberwithint:0.0])); //nslog (@ "" "" "" ""%@ "lineString"); [Linesarray addobject:linestring]; } cgpathrelease (path); cfrelease (frame); cfrelease (Framesetter); return (nsarray *) Linesarray;}
Article Reference links
The count of the array returned by the function is the number of literal lines in the label, and the elements in the array are the contents of a row.
Reprint please specify the source:
Original address: Http://mingxianwei.github.io/2016/05/27/iOS the number of lines of text in a label and the contents of each line
Small potatoes
Find the number of lines of text in the label and the contents of each line in iOS