UITextField UITextView and UILabel in IOS calculate height according to content

  • 2021-12-05 07:34:55
  • OfStack

UITextField, UITextView and UILabel in IOS calculate height according to content

In the process of development, we often encounter the situation that the height of controls is determined according to the content. The common controls are UITextField, UITextView and UILabel. The following 1UITextView is an example to illustrate 1:

First, a new textView will be built. Facilities text and font

 UITextView *textView = [[UITextView alloc] init];
  textView.text = @"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";
  textView.font = [UIFont systemFontOfSize:14];
 float width =200;
 float height =[self heightForString:textView.text fontSize:14 andWidth:width];
 textView.frame = CGRectmake(0,0,width,height);
  [self.view addSubview:textView];

Method for calculating textview height

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

1 This method can meet the common requirements in all cases

Related articles: