Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change height of UITableViewCell when constraint changes?

My question is related to this one: How to change height Constraint of UIView in UitableviewCell when using UITableViewAutomaticDimension

The solution there does not seem to be working for me.

enter image description here

In the image above i have a simple cell. On tap of cell, i want to change the constraint of the redView to be larger. This should then automatically change the height of the cell.

I already have the height constraint of the cell set to an @IBOutlet and i think i am correctly changing the size of the cell, but it is not working.

Here is my sample app that is not working. Any help? SampleApp - for Xcode 9.3

like image 357
Just a coder Avatar asked Aug 31 '25 22:08

Just a coder


2 Answers

You need to set a bottom constraint to the red view so auto-layout can stretch the cell after setting the constant value

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()
    }
}
like image 96
Sh_Khan Avatar answered Sep 03 '25 13:09

Sh_Khan


Calling the below will recalculate the heights.

[tableView beginUpdates];
[tableView endUpdates];
like image 41
particleman Avatar answered Sep 03 '25 13:09

particleman