iOS calculates the height of the string, with the need for a friend to refer to below.
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 own 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)//for calculating the rectangular block occupied 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 object contains information that will be used for text drawing. This 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 returned height plus pixels (up and down the padding), so that the Uitextview really adapt 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;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS calculates Uitextview height based on string