约束更改时如何更改UITableViewCell的高度?

iOS*_*com 1 uitableview ios swift

我的问题与此相关:使用UITableViewAutomaticDimension时如何在UitableviewCell中更改UIView的高度约束

那里的解决方案似乎对我不起作用。

在此处输入图片说明

在上图中,我有一个简单的单元格。在单元格上点击,我想将redView的约束更改为更大。然后,这将自动更改单元格的高度。

我已经将单元格的高度约束设置为@IBOutlet,我认为我正确地更改了单元格的大小,但是它不起作用。

这是我的示例应用程序无法正常工作。有什么帮助吗?SampleApp-适用于Xcode 9.3

par*_*man 5

调用下面将重新计算高度。

[tableView beginUpdates];
[tableView endUpdates];
Run Code Online (Sandbox Code Playgroud)


Sh_*_*han 5

您需要为红色视图设置底部约束,以便在设置常数值后自动布局可以拉伸像元

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "c", for: indexPath) as! customcell
        configure(cell: cell, indexPath: indexPath)
        cell.redview.backgroundColor = .red
        cell.selectionStyle = .none
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! customcell
        cell.constraint.constant = data[indexPath.row] == "contracted"  ? 30 : 200
        data[indexPath.row] = data[indexPath.row] == "contracted" ? "expanded" : "contracted"
        tableView.reloadData()
    }

    func configure(cell: customcell, indexPath: IndexPath) {
        let data = self.data[indexPath.row]
        if data == "expanded" {
            cell.constraint.constant = 200
        } else {
            cell.constraint.constant = 30
        }

        cell.layoutIfNeeded()
    }
}
Run Code Online (Sandbox Code Playgroud)