IOS calculates the UITextView height based on the string
IOS calculates the string height. For more information, see.
Method 1: applicable before ios7.0
/** @ Method: Get the specified width and width, fontSize, the height of the string value @ param value the string to be calculated @ param fontSize the font size @ param Width limits the Width of the string display area @ result float returns the height */-(float) heightForString :( NSString *) value fontSize :( float) fontSize andWidth :( float) width {CGSize rows = [value sizeWithFont: [UIFont systemFontOfSize: fontSize] rows: CGSizeMake (width-16.0, width) lineBreakMode: NSLineBreakByWordWrapping]; // The line feed type (lineBreakMode) can be set as needed. height + 16.0 ;}
Method 2: ios7.0 and later
/** @ Method: Get the specified width and width, fontSize, the height of the string value @ param value the string to be calculated @ param fontSize the font size @ param Width limits the Width of the string display area @ result float returns the height */-(float) heightForString :( NSString *) value andWidth :( float) width {// get the attribute NSAttributedString * attrStr = [[NSAttributedString alloc] initWithString: value]; _ text. attributedText = attrStr; nsange range = NSMakeRange (0, attrStr. length); // get the attributedStri of the segment Ng attribute dictionary NSDictionary * dic = [attrStr attributesAtIndex: 0 20.tiverange: & range]; // calculate the text size CGSize sizeToFit = [value boundingRectWithSize: CGSizeMake (width-16.0, MAXFLOAT) // used to calculate the rectangular block occupied during text painting options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // additional option attributes: dic // The text attribute context: nil]. size; // context. Including some information, such as how to adjust the font spacing and zoom. The information contained in this object will be used for text painting. This parameter can be nil return sizeToFit. height + 16.0 ;}
// Note: in the first two methods, UITextView has an 8px padding between top and bottom. You need to subtract UITextView. contentSize. width by 16 pixels (the Left and Right padding is 2 x 8px ). At the same time, 16 pixels (upper and lower padding) are added to the returned height, so that UITextView can truly adapt to the height of the content. For example, in the Code CGSizeMake (width-16.0, CGFLOAT_MAX), return sizeToFit. height + 16.0. Not in UILable
Method 3: General (recommended)
/** @ Method: gets the height of the string with the specified width on UITextView @ param textView the UITextView to be calculated @ param Width limits the width of the 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 ;}