首页 > 解决方案 > TableViewCell 受制图限制,高度不正确

问题描述

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

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

评论单元格

我已经设置了tableView.estimatedRowHeight = 60,细胞是clipsToBounds = false

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

以下是我使用制图框架为 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, bottomView, 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 的顶部设置为评论标签的底部,也没有底部约束。我认为这允许动态高度工作。在底部视图的约束中没有使用上面注释掉的约束,它仍然是重叠的。我知道重叠是由单元格上的 clipsToBounds 设置为 false 引起的,因此单元格的高度是问题所在。

看起来是这样的:

在此处输入图像描述

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

标签: iosswiftuitableviewconstraintscartography

解决方案


所以我意识到使用单元格self.contentView而不是 just所需的所有约束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, bottomView, userImageView in
    bottomView.top == msgLabel.bottom
    bottomView.right == msgLabel.rightMargin
    bottomView.left == userImageView.right + Geometry.messageLabelLeftOffset
    bottomView.bottom == contentView.bottom
}

推荐阅读