UITableView dynamic cell heights only correct after some scrolling

后端 未结 24 1226
误落风尘
误落风尘 2020-11-29 16:41

I have a UITableView with a custom UITableViewCell defined in a storyboard using auto layout. The cell has several multiline UILabels.

24条回答
  •  失恋的感觉
    2020-11-29 17:30

    In Swift 3. I had to call self.layoutIfNeeded() each time I update the text of the reusable cell.

    import UIKit
    import SnapKit
    
    class CommentTableViewCell: UITableViewCell {
    
        static let reuseIdentifier = "CommentTableViewCell"
    
        var comment: Comment! {
            didSet {
                textLbl.attributedText = comment.attributedTextToDisplay()
                self.layoutIfNeeded() //This is a fix to make propper automatic dimentions (height).
            }
        }
    
        internal var textLbl = UILabel()
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            if textLbl.superview == nil {
                textLbl.numberOfLines = 0
                textLbl.lineBreakMode = .byWordWrapping
                self.contentView.addSubview(textLbl)
                textLbl.snp.makeConstraints({ (make) in
                    make.left.equalTo(contentView.snp.left).inset(10)
                    make.right.equalTo(contentView.snp.right).inset(10)
                    make.top.equalTo(contentView.snp.top).inset(10)
                    make.bottom.equalTo(contentView.snp.bottom).inset(10)
                })
            }
        }
    }
    

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let comment = comments[indexPath.row]
            let cell = tableView.dequeueReusableCell(withIdentifier: CommentTableViewCell.reuseIdentifier, for: indexPath) as! CommentTableViewCell
            cell.selectionStyle = .none
            cell.comment = comment
            return cell
        }
    

    commentsTableView.rowHeight = UITableViewAutomaticDimension
        commentsTableView.estimatedRowHeight = 140
    

提交回复
热议问题