IOS 中UITextField,UITextView,UILabel 根据内容来计算高度
IOS中UITextField,UITextView,UILabel根据内容来计算高度
在开发的过程中,常常遇到根据内容来决定控件的高度的情况,常见的就是UITextField,UITextView,UILabel这三个控件,下面一UITextView为例来说明一下:
首先新新建一个textView.设施text,font
UITextView*textView=[[UITextViewalloc]init]; textView.text=@"2015-01-1914:07:47.290MicroPort[3047:103721]-[PPRevealSideViewControllergestureRecognizerDidTap:][Line1463]Yes,thetapgestureisanimated,thisisnormal,notabug!Isthereanybodyherewithanonanimateinterface?:P"; textView.font=[UIFontsystemFontOfSize:14]; floatwidth=200; floatheight=[selfheightForString:textView.textfontSize:14andWidth:width]; textView.frame=CGRectmake(0,0,width,height); [self.viewaddSubview:textView];
计算textview高度的方法
-(float)heightForString:(NSString*)valuefontSize:(float)fontSizeandWidth:(float)width//根据字符串的的长度来计算UITextView的高度 { floatheight=[[NSStringstringWithFormat:@"%@\n",value]boundingRectWithSize:CGSizeMake(width,CGFLOAT_MAX)options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeadingattributes:[NSDictionarydictionaryWithObjectsAndKeys:[UIFontsystemFontOfSize:fontSize],NSFontAttributeName,nil]context:nil].size.height; returnheight; }
一般情况下常见的需求这个方法都能够满足