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; }
一般情況下常見的需求這個方法都能夠滿足
新聞熱點
疑難解答