如何在自动布局中使用UITableViewCell的动态高度,当底部视图隐藏时移动其他视图到上方?

7

我有一个位于xib文件中的UITableViewCell以及位于相应的UITableViewCell子类中的outlets。我正在从以下方法中返回cell的高度:

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

return 400

}

我需要根据表格中每行的数据隐藏一些视图,底部视图应该移动到单元格的顶部。当我从单元格隐藏视图时,隐藏视图处会留下空白,底部视图不会移动到单元格的顶部。

这里是我如何隐藏单元格视图。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    .....
    cell.opetion4.isHidden = true
    cell.opetion3.isHidden = true

}

这是我的单元格。

进入图像描述

隐藏2个中间标签后,它看起来如下所示。

进入图像描述

但我想要移除这个空白空间,并将底部标签转移到顶部,如下所示。

进入图像描述

3个回答

5
首先,将 UITableViewCell 的高度设置为 UITableView.automaticDimension
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

将所有的questionLabels嵌入一个UIStackView(垂直方向),不包括bottomLabel。在UIStackView和bottomLabel之间设置AutoLayoutConstraint。

enter image description here

UILabelnumberOfLines 属性设置为 0(零)。

enter image description here

UIStackViewDistribution 设置为 Fill

enter image description here

然后,在你的tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell方法中隐藏标签。它会自动处理UILabel之间的空格。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell

    cell.questionLabel1.text = labelOneText[indexPath.row]
    cell.questionLabel2.text = labelTwoText[indexPath.row]
    cell.questionLabel3.text = labelThreeText[indexPath.row]

    if labelOneText[indexPath.row] == "" {
        cell.questionLabel1.isHidden = true
    }

    if labelTwoText[indexPath.row] == "" {
        cell.questionLabel2.isHidden = true
    }

    if labelThreeText[indexPath.row] == "" {
        cell.questionLabel3.isHidden = true
    }

    return cell
}

最终输出:

enter image description here


2

首先,我建议您将UITableViewCell的高度设置为automatic dimensions。将所有子项连接在一起,并将最后一个子项连接到xib的uiview。现在隐藏视图不会调整单元格的大小,因此您需要玩弄要隐藏的uiview的高度约束。

IBOutlet中将高度约束设置为强约束,否则会崩溃,因为单元格正在重用,一旦设置了constraint,它将变成nil。您需要确保根据显示单元格的要求更改高度约束,即为每个cell维护一些datasource,以便每次调用cellforrowatIndexpath方法时决定显示或隐藏视图。

希望这能帮助到您。


2
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) ->CGFloat {

return UITableView.automaticDimension

}

现在,在单元格中,将您想要隐藏/显示的所有视图及其兄弟视图放入 UIStackView(水平) 中。现在,如果您隐藏了一个视图,它将被隐藏,其空间也将被隐藏,因此不会显示任何空白,并且无需处理额外的约束条件。这将由 stackview 处理。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接