ios - UILabel Text Multi Line given width of text -


i want scale uilabel how snapchat does. have textfield insert text. when tapping done textfield goes , label's text set. want insert multiple lines when text larger width of screen , truncate frame of label text fits.

here code

if(iscaption){     //begin edit text     _textlabel.hidden = no;     _textlabel.text = currenttext;     _textfieldoutlet.hidden = yes;     [_textfieldoutlet settextalignment:nstextalignmentleft];     [_textlabel settextalignment:nstextalignmentleft];     [self.screenshotview bringsubviewtofront:_textlabel];      _textlabel.frame = cgrectmake(10,                                   _textlabel.frame.origin.y,                                   [currenttext sizewithattributes:@{nsfontattributename:[_textlabel font]}].width,                                   [currenttext sizewithattributes:@{nsfontattributename:[_textlabel font]}].height);       isediting = yes;     iscaption = no;   } 

the problem result huge line of text , want spreads on multiline. how can accomplished? how can separate lines given width?

if want multiple lines should not calculate width sizewithattributes: . should fix width label , calculate height boundingrectwithsize: method.

you can create helper method follows:

- (cgsize)suggestedsizewithfont:(uifont *)font size:(cgsize)size linebreakmode:(nslinebreakmode)linebreakmode forstring:(nsstring *)text {       nsmutableparagraphstyle *paragraphstyle = [nsmutableparagraphstyle new];       paragraphstyle.linebreakmode = linebreakmode;       nsattributedstring *attributedstring = [[nsattributedstring alloc] initwithstring:text attributes:@{nsfontattributename: font,       nsparagraphstyleattributename: paragraphstyle}];       cgrect bounds = [attributedstring boundingrectwithsize:size options:nsstringdrawinguseslinefragmentorigin context:nil];       return bounds.size; } 

or can create category , rid of text parameter.

then can call method label's text follows:

cgsize requiredsize = [self suggestedsizewithfont:_textlabel.font size:cgsizemake(self.view.frame.size.width, cgfloat_max) linebreakmode:_textlabel.linebreakmode forstring:_textlabel.text]; _textlabel.frame = cgrectmake(0, _textlabel.frame.origin.y, requiredsize.width, requiredsize.height); 

you can set width whatever want label fit in. height calculated accordingly. remember set numberoflines 0.


Comments