Swift - TableViewCell高度动态计算

本文介绍了在iOS8中如何利用Auto Layout动态计算TableViewCell的高度。关键步骤包括:1) 使用Auto Layout为UITableViewCell的子视图添加约束;2) 设置tableView的rowHeight为UITableViewAutomaticDimension;3) 设置estimatedRowHeight,或者实现预估高度代理方法。通过这些设置,当cell滚动出屏幕时,其高度将自动根据内容计算。注意,还需确保最后一个子视图与contentView底部有约束,以获得正确高度。
摘要由CSDN通过智能技术生成

在iOS8,我们为了允许cell自动计算高度,必须注意以下几点:


1:当创建UITableViewCell的时候使用Auto Layout布局子视图,添加对应的约束( leading, top, trailing and bottom constraints)

2:设置tableView的rowHeight为UITableViewAutomaticDimension

3:设置estimatedRowHeight或者是实现预估高度代理方法,该值非0即可,或者设置为cell的一半


设置estimatedRowHeight表示为cell设置一个临时的高度或者说是占位高度。滚动tableView的时候当cell即将出屏幕时,cell的高度即将被计算,为了确定cell实际的高度,tableView会询问每一个cell的高度,而cell的高度是基于它的contentView的高度,由于我们在布局的时候使用了Auto Layout为contentView添加了与子视图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要根据文字内容自动撑开TableViewCell高度,可以按照以下步骤操作: 1. 首先,在TableViewCell中添加一个UILabel,并设定好约束。 2. 在TableView的代理方法中,实现heightForRowAt方法。该方法返回值为该行的高度。在该方法中,计算UILabel的高度,并返回该高度。代码如下: ```swift func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let text = dataArray[indexPath.row] let width = UIScreen.main.bounds.size.width - 20 let font = UIFont.systemFont(ofSize: 17) let size = CGSize(width: width, height: CGFloat(MAXFLOAT)) let paragraph = NSMutableParagraphStyle() paragraph.lineBreakMode = .byWordWrapping let attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.paragraphStyle: paragraph] let rect = text.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil) return rect.height + 20 } ``` 3. 在TableViewCell中,设置UILabel的numberOfLines为0,并设定好约束。 4. 在TableView的代理方法中,实现cellForRowAt方法。在该方法中,设置UILabel的text属性。代码如下: ```swift func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let label = cell.viewWithTag(100) as! UILabel label.text = dataArray[indexPath.row] return cell } ``` 这样,就可以根据文字内容自动撑开TableViewCell高度了。其中,dataArray是存储文字内容的数组。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值