1. With Xib, the height of the lable is not set when the constraint is set, and the height returned is the optimal height.
2. Calculate Height with lable code
CGFloat getheightforlablestring (nsstring *value,cgfloat width,uifont * font) { * Lable=[[uilabel alloc] Initwithframe:cgrectmake (00)]; Lable.text= value; 0 ; = font; return [lable sizethatfits:cgsizemake (width, maxfloat)].height;}
3. New functions to be used after iOS7
maxfloat) options:nsstringdrawinguseslinefragmentorigin| Nsstringdrawingusesfontleading attributes:@{nsfontattributename: _contentlable.font} context:nil].size.height;
4.
/* * */-(float) heightforstring: (NSString *) value fontSize: (float) fontSize andwidth: ( float) width{ = [value Sizewithfont:[uifont systemfontofsize:fontsize] Constrainedtosize: Cgsizemake (width, cgfloat_max) linebreakmode:uilinebreakmodewordwrap]; // the newline Type here (Linebreakmode) can be set according to your own situation return sizetofit.height;}
5.UITextView Compute Height
/** @method Gets the height of the specified width, the font size fontSize, the string value @param value the string to be evaluated @param the size of the FontSize font @param width limit the widths of the string display area @r Esult float returns the height*/- (float) Heightforstring: (NSString *) value andwidth: (float) width{//gets the properties of the current textNsattributedstring *attrstr =[[Nsattributedstring alloc] initwithstring:value]; _text.attributedtext=Attrstr; Nsrange Range= Nsmakerange (0, attrstr.length); //Gets the attribute dictionary for the segment attributedstringNsdictionary *dic = [Attrstr attributesatindex:0effectiverange:&Range]; //calculate the size of textCgsize SizeToFit = [Value boundingrectwithsize:cgsizemake (Width-16.0, maxfloat)//a rectangular block that is used to calculate the text that is occupied when drawingOptions:nsstringdrawinguseslinefragmentorigin | Nsstringdrawingusesfontleading//additional options When text is drawnAttributes:dic//Properties of textContext: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 returnSizetofit.height +16.0;}
iOS string Calculation Height summary