IOSでUICTextField、UICTextView、UICLabelは内容によって高さを計算します。


IOSでUICTextField、UICTextView、UICLabelは内容によって高さを計算します。
開発の過程で、常に内容によってコントロールの高さを決めることがあります。よくあるのはUIText Field、UIText View、UICLabelの3つのコントロールです。次のUIText Viewの例を説明します。
まず、新しいtextView施設textを作成します。

 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];

textviewの高さを計算する方法

- (float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width//            UITextView   
{
  float height = [[NSStringstringWithFormat:@"%@
",value] boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeadingattributes:[NSDictionarydictionaryWithObjectsAndKeys:[UIFontsystemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil].size.height; return height; }
一般的によくある需要はこの方法で全部満足できます。