IOS中UITextField,UITextView,UILabel如何根据内容来计算高度
更新:HHH   时间:2023-1-8


这篇文章将为大家详细讲解有关IOS中UITextField,UITextView,UILabel如何根据内容来计算高度,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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

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

关于“IOS中UITextField,UITextView,UILabel如何根据内容来计算高度”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

返回移动开发教程...