欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

IOS 中UITextField,UITextView,UILabel 根据内容来计算高度

程序员文章站 2024-02-14 16:39:58
ios 中uitextfield,uitextview,uilabel 根据内容来计算高度 在开发的过程中,常常遇到根据内容来决定控件的高度的情况,常见的就是uitext...

ios 中uitextfield,uitextview,uilabel 根据内容来计算高度

在开发的过程中,常常遇到根据内容来决定控件的高度的情况,常见的就是uitextfield,uitextview,uilabel这三个控件,下面一uitextview 为例来说明一下:

首先新新建一个textview. 设施text,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];

计算textview高度的方法

- (float)heightforstring:(nsstring *)value fontsize:(float)fontsize andwidth:(float)width//根据字符串的的长度来计算uitextview的高度
{
  float height = [[nsstringstringwithformat:@"%@\n ",value] boundingrectwithsize:cgsizemake(width, cgfloat_max) options:nsstringdrawinguseslinefragmentorigin | nsstringdrawingusesfontleadingattributes:[nsdictionarydictionarywithobjectsandkeys:[uifontsystemfontofsize:fontsize],nsfontattributename, nil] context:nil].size.height;
  
  return height;
  
}

一般情况下常见的需求这个方法都能够满足