AutoLayout constraint reset after tableView cell is created.

In the process of acquiring images asynchronously from a website and displaying them in an imageView in a tableView cell, I am implementing a process to reset the heightConstraint of the imageView to match the aspect ratio of the acquired image.

In this process, if the image is acquired after the cell is created, the height will not change even if the imageView's heightConstraint is reset.

So I ran tableView.reloadRows(at: [indexPath], with: .none) after retrieving the image and it displayed correctly.

Is this correct solution?

Is it correct to assume that if I change the autolayout constraint of an object in a cell after the cell is created, it will not be reflected in the screen display unless I reload the cell?

Answered by Claude31 in 710214022

I would call reload as well. You get the same result if you scroll the cell out of view and scroll back, because it calls reload.

But you may likely use beginUpdate. Read here:

https://stackoverflow.com/questions/40534265/uitableviewcell-layout-not-updating-until-cell-is-reused

Accepted Answer

I would call reload as well. You get the same result if you scroll the cell out of view and scroll back, because it calls reload.

But you may likely use beginUpdate. Read here:

https://stackoverflow.com/questions/40534265/uitableviewcell-layout-not-updating-until-cell-is-reused

It is effectively safe to do so. And not a significant overload.

However, I tested a case where I just change the constant of a constraint, and it redraws without calling reload.

So try to call setNeedsLayout on the cell, instead of reload and tell what you get.

If you need further investigation, you should post the code (and show how you defined the constraints, the cell dimension, …)

The following is a part of my code;

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    ...
    if let url = URL(string: urlString) {
        cell.imageView.sd_setImage(with: url, completed: { image, error, _, _ in
            if let error = error {
                print(error)
                return
            }
            if let image = image {
                let imageAspect = image.size.height / image.size.width
                cell.imageViewHeightConstraint.constant = tableView.frame.width * imageAspect
                tableView.reloadRows(at: [indexPath], with: .none)
            }
        })
     }
    ...
}

I tried to call setNeedsLayout on the cell by replacing tableView.reloadRows(at: [indexPath], with: .none) with cell.setNeedsLayout(), it did not work.

Anyway, thank you for your information.

AutoLayout constraint reset after tableView cell is created.
 
 
Q