iOS calculates the height of the string, with the need for friends to take the test.
Method one: Applicable before ios7.0
/** @method Gets the height of the specified width, font size fontSize, String value @param value the string to be evaluated @param the size of the FontSize font @param the width of the string display area @res Ult Float return height */-(float) heightforstring: (NSString *) value fontSize: (float) fontSize andwidth: (float) width{ Cgsize SizeToFit = [value Sizewithfont:[uifont systemfontofsize:fontsize] constrainedtosize:cgsizemake (Width- 16.0, Cgfloat_max) linebreakmode:nslinebreakbywordwrapping]; The newline type (Linebreakmode) here can be set according to your actual situation return sizetofit.height + 16.0;}
method Two: ios7.0 and later apply
/** @method Gets the height of the specified width, font size fontSize, String value @param value the string to be evaluated @param the size of the FontSize font @param the width of the string display area @res Ult Float Returns the height */-(float) heightforstring: (NSString *) value andwidth: (float) width{//Gets the properties of the current text nsattributedstring *ATTRSTR = [[Nsattributedstring alloc] initwithstring:value]; _text.attributedtext = Attrstr; Nsrange range = nsmakerange (0, attrstr.length); Gets the attribute dictionary for the segment attributedstring nsdictionary *dic = [Attrstr attributesatindex:0 effectiverange:&range]; Calculates the size of the text cgsize SizeToFit = [Value Boundingrectwithsize:cgsizemake (width-16.0, maxfloat)//used to calculate the occupied rectangle block when the text is drawn Options:nsstringdrawinguseslinefragmentorigin | Nsstringdrawingusesfontleading//Text drawing additional Options attributes:dic//Text properties Context:nil].size; Context contexts. Includes information such as how to adjust word spacing and zoom.The information that the object includes will be used for text drawing.
The parameter can be nil return sizetofit.height + 16.0;}
Note: In the first two methods , Uitextview has a 8px padding on the upper and lower left , whichrequires UITextView.contentSize.width minus pixels (left and right padding 2 x 8px). At the same time, the height returned is added to the pixel (upper and lower padding). This is what Uitextview really adapts to the content of the height. such as code in cgsizemake (width-16.0, Cgfloat_max),return sizetofit.height + 16.0.
not in the uilable.
Method Three: Universal (recommended)
/** @method Gets the height of the string on Uitextview that specifies width widths @param textView The width of the Uitextview @param width limit string display area @result float returns the height */ -(float) heightforstring: (Uitextview *) TextView andwidth: (float) width{cgsize sizetofit = [TextView sizethatfits : Cgsizemake (width, maxfloat)]; return sizetofit.height;}
iOS calculates Uitextview height based on string