UITableViewCell 动态高度计算

作者: 我叫大大虾米 | 来源:发表于2016-06-21 23:04 被阅读584次

    平时的开发中我们打交道最多的的可能就是UITableVIew了,那今天我们就总结下其动态显示高度的多种解决方法

    Method 1 - iOS 8为我们提供的方法

    self.tableView.rowHeight = UITableViewAutomaticDimension;
       
    或者我们可以实现返回高度的代理方法
       
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
       return UITableViewAutomaticDimension;
    }
    

    Method 2 - systemLayoutSizeFittingSize

     CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
     return 1  + size.height;   
     
     
    

    如果说我们的UILable要多行显示的话要设置numberOfLines等于0,
    xib的话还要设置UIlable的preferredMaxLayoutWidth

    Method 3 - sizeWithFont

    - (CGSize)sizeWithFont:(UIFont *)font 
        constrainedToSize:(CGSize)size      
            lineBreakMode:(NSLineBreakMode)lineBreakMode         
    

    由于该方法在iOS7之后已经弃用我们可以用其替代方法来计算字符串的高度

    Method 4 - 第三方库

    大家应该熟知早前在百度知道团队的哥们的一个库UITableView-FDTemplateLayoutCell(runtime + method swizzing实现)

    详情请参考Demo-https://github.com/LargeShrimp/UITableViewCellDynamicHeight

    相关文章

      网友评论

        本文标题: UITableViewCell 动态高度计算

        本文链接:https://www.haomeiwen.com/subject/wjigdttx.html