TableViewCell 受制图限制,高度不正确

问题描述

我正在使用具有动态单元格高度的 UITableView 构建评论功能。我正在使用 Cartography 框架以编程方式设置每个单元格内容的约束,因为此表视图未在故事板中设置。

我的评论标签与下方的单元格重叠有问题。 具有短注释字符串的单元格看起来不错,这是一个示例 SS:

CommentCell

我已经设置了 tableView.estimatedRowHeight = 60,单元格是 clipsToBounds = false

func tableView(_: UITableView,heightForRowAt indexPath: IndexPath) -> CGFloat {
    UITableView.automaticDimension
}

以下是我使用 Cartography 框架为 Cell 的不同子视图设置的约束:

 // User Image View
 constrain(self,userImageView) {
        $1.height == 36.0
        $1.width == 36.0
        $1.left == $0.left + 16.0
        $1.top == $0.top + 12.0
        $1.bottom == $0.bottom - 12.0 ~ UILayoutPriority(500)
 }
 
 // Comment Label
 constrain(self,commentLabel,userImageView) {
        $1.top == $2.top - 6.0
        $1.right == $0.right - (18.0 + Geometry.likeButtonWidth)
        $1.left == $2.right + Geometry.messageLabelLeftOffset
    }
 
 // Bottom view - ( comment_time / LikeCount / Reply )
 constrain(self.contentView,messageLabel,bottomView,userImageView) { contentView,msgLabel,userImageView in
    
      bottomView.top == msgLabel.bottom
      bottomView.right == msgLabel.rightMargin
      bottomView.left == userImageView.right + Geometry.messageLabelLeftOffset
    
      // contentView.bottom == bottomView.bottom // very tall cell is overlapping cells below with this line
      // contentView.height == msgLabel.height + 20 // cell is twice as tall,leaving large empty gap,but not overlapping
 }

评论标签没有设置底部约束。

bottonView 将其顶部设置为评论标签底部,也没有底部约束。我认为这允许动态高度起作用。 在bottomView的约束中没有使用上面注释掉的约束,它仍然是重叠的。我知道重叠是由单元格上的 clipsToBounds 设置为 false 引起的,因此单元格的高度是问题所在。

这是它的样子:

enter image description here

如何让单元格高度适合内容

解决方法

所以我意识到使用单元格的 self.contentView 而不仅仅是 self 所需的所有约束,我之前尝试过这个并且它没有正确呈现,但那是因为并非所有的垂直约束都存在你可以在上面看到。所以它应该是这样的:

// User Image View
constrain(self.contentView,userImageView) {
    $1.height == 36.0
    $1.width == 36.0
    $1.left == $0.left + 16.0
    $1.top == $0.top + 12.0
    //$1.bottom == $0.bottom - 12.0 ~ UILayoutPriority(500) removed this
}

// Comment Label
constrain(self.contentView,commentLabel,userImageView,bottomView) {
    $1.top == $2.top - 6.0
    $1.right == $0.right - (18.0 + Geometry.likeButtonWidth)
    $1.left == $2.right + Geometry.messageLabelLeftOffset
    $1.bottom == $3.top
}

// Bottom view - ( comment_time / LikeCount / Reply )

constrain(self.contentView,messageLabel,bottomView,userImageView) { contentView,msgLabel,userImageView in
    bottomView.top == msgLabel.bottom
    bottomView.right == msgLabel.rightMargin
    bottomView.left == userImageView.right + Geometry.messageLabelLeftOffset
    bottomView.bottom == contentView.bottom
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...