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 = [[ NSString stringWithFormat : @"%@\n " ,value] boundingRectWithSize : CGSizeMake (width, CGFLOAT_MAX ) options : NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes :[ NSDictionary dictionaryWithObjectsAndKeys :[ UIFont systemFontOfSize :fontSize], NSFontAttributeName , nil ] context : nil ]. size . height ;
   
   
return height;
   
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值