UITextView自适应高度

博客介绍了在遇到UITextView计算文字高度不准确的问题时,如何通过Stack Overflow找到的解决方案,提供了相关的代码示例。

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

   之前textView算文字高度总是拿不到合适的高度。在Stack Overflow 找到了解决方法备注在此。

代码如下:

 UITextView * textView=[[UITextView alloc] initWithFrame:CGRectMake(20, 40, self.view.frame.size.width-40, 20)];
    textView.text=@"   I'm porting one of apps from iOS 6.1 to iOS 7. I'm using a layout where there's a UITextView that has a fix width, but it's height is based on its contentsize. For iOS 6.1 checking the contentsize.height and setting it as the textview's frame height was enough, but it doesn't work on iOS 7.\n  How can i then create a UITextView with a fixed width, but dynamic height based on the text it's showing? \n";
    textView.textColor=[UIColor brownColor];
    textView.font=[UIFont systemFontOfSize:14.0];
    textView.layer.borderColor=[[UIColor lightGrayColor] CGColor];
    textView.layer.borderWidth=1.0f;
    [self.view addSubview:textView];
        
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    textView.frame = newFrame;
下面是这个demo:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值