如何设置UITableViewCell中cell内容的自适应高度

IOS7之后有很多方法被弃用,也有很多方法添加上了。问题一大堆,我的学习方法让我越往后学,花的时间越来越多。一个方法,我不单单想知道它怎么实现,而且一定要知道为什么样实现,还能怎么样实现。

今天学习的时候,遇到一个问题,由于看教学视频,版本比较老,而我又是一个新手,没办法。一点点学吧。

问题就是设置UITableViewCell中cell内容的自适应高度。

在ios7之前有这么个方法:

<span style="font-size:18px;color:#666600;"><strong> [text sizeWithFont: constrainedToSize:];</strong></span>

但是现在被废除掉了,改用:

<span style="font-size:18px;color:#666600;"><strong>[text boundingRectWithSize:options: attributes:context:];
</strong></span>

可能这样说不明白怎么用,直接上代码:

创建表视图:

<span style="font-size:18px;color:#666600;"><strong>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    NSString *text = _content[indexPath.row];
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.text = text;
    cell.textLabel.font = [UIFont systemFontOfSize:10];
    cell.backgroundColor= [UIColor clearColor];
    
    return cell;
    
}
</strong></span>

设置自适应:

<span style="font-size:18px;color:#666600;"><strong>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    UITableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
    NSString * text = [_content objectAtIndex:indexPath.row];

//    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:15.0]};
    CGSize textSize = [text boundingRectWithSize:tableView.bounds.size options:NSStringDrawingUsesFontLeading attributes:nil context:nil].size;
    return textSize.height;
    
}
</strong></span>

其中有一个值得注意的地方:

<span style="font-size:18px;color:#666600;"><strong>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    UITableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];</strong></span>
如果这里用这个方法的话,会程序会不断的调用这个地方的方法,程序执行顺序是,先绘制高度,然后再创建cell的实例,此时,cell并没有绘制出来,是一个nil.


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值