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

Ios 如何在自动布局中使用UITableViewCell的动态高度,并在隐藏底部视图时将其他视图向上移动?,ios,swift,uitableview,Ios,Swift,Uitableview,我在xib中有一个UITableViewCell,它的输出在相应的UITableViewCell子类中。我正在从中返回单元格的高度 func tableView(tableView:UITableView,heightForRowAt indexath:indexPath)->CGFloat{ 返回400 } 我需要根据表中每一行的可用数据隐藏一些视图,并且底部视图应该移到单元格的顶部。当我对单元格隐藏视图时,隐藏视图的位置会留下空白,底部视图不会移动到单元格的顶部。 下面是我如何隐藏单元格视

我在xib中有一个UITableViewCell,它的输出在相应的UITableViewCell子类中。我正在从中返回单元格的高度

func tableView(tableView:UITableView,heightForRowAt indexath:indexPath)->CGFloat{
返回400
}
我需要根据表中每一行的可用数据隐藏一些视图,并且底部视图应该移到单元格的顶部。当我对单元格隐藏视图时,隐藏视图的位置会留下空白,底部视图不会移动到单元格的顶部。

下面是我如何隐藏单元格视图的

func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
.....
cell.opetion4.ishiden=true
cell.opetion3.ishiden=true
}
这是我的手机

隐藏2个中间标签后,其外观如下所示

但我想删除这个空白,并希望将底部标签移到顶部,如下所示


首先,我建议您将
UITableViewCell
高度设置为
自动标注
。将所有子项彼此连接,最后一个子项连接到xib的
uiview
。现在隐藏视图不会调整单元格的大小,所以您需要使用要隐藏的
uiview
的高度约束

IBOutlet
中将高度约束设置为强约束,否则它将崩溃,因为单元格正在重新使用,
constraint
设置一次后将变为
nil
。您需要确保高度约束根据显示单元格的要求而改变,这意味着对于每个
单元格
来说,每次调用
cellforrowatinexpath
方法时,都要维护一些决定显示或隐藏视图的
数据源

希望这有帮助

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

return UITableView.automaticDimension

}

现在在单元格中,将所有视图和要隐藏/显示的同级视图放入
UIstackview(水平)
。现在,如果您隐藏一个视图,它将被隐藏,其空间也将被隐藏,不会显示空白,并且不需要处理额外的约束。它将首先由
stackview

处理,将UITableView单元格的高度设置为
UITableView.automaticDimension

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}
将所有问题标签嵌入
UIStackView
(垂直)中,不包括
bottomLabel
。在
UIStackView
bottomLabel
之间设置AutoLayoutConstraint

UILabel
s的
numberOfLines
属性设置为0(零)

UIStackView
分布设置为
Fill

然后,在
tableView(\utableview:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell
方法中隐藏标签。它将自动处理
UILabel
s之间的空格

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
}
最终输出: