SoFunction
Updated on 2025-04-03

UITextField, UITextView, UILabel in IOS calculate height based on content

UITextField, UITextView, UILabel in IOS calculate height based on content

During the development process, we often encounter situations where the height of the control is determined based on the content. The common ones are UITextField, UITextView, and UILabel. The following UITextView is an example to illustrate:

First create a new textView. Facility text, font

 UITextView *textView = [[UITextView alloc] init];
   = @"2015-01-19 14:07:47.290 MicroPort[3047:103721] -[PPRevealSideViewController gestureRecognizerDidTap:] [Line 1463] Yes, the tap gesture is animated, this is normal, not a bug! Is there anybody here with a non animate interface? :P";
   = [UIFont systemFontOfSize:14];
 float width =200;
 float height =[self heightForString: fontSize:14 andWidth:width];
  = CGRectmake(0,0,width,height);
  [ addSubview:textView];

Methods to calculate the height of textview

- (float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width// Calculate the height of the UITextView based on the length of the string{
  float height = [[NSStringstringWithFormat:@"%@\n ",value] boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeadingattributes:[NSDictionarydictionaryWithObjectsAndKeys:[UIFontsystemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil].;
  
  return height;
  
}

In general, this method can meet common needs