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

本文介绍了一种根据UITextView内容自动调整其高度的方法。通过计算文本的实际高度来确保控件大小适应内容变化,适用于iOS应用开发中需要动态调整布局的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发的过程中,常常遇到根据内容来决定控件的高度的情况,常见的就是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;
   
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值