0
votes

I've stack view inside table cell which contains three views. I want the stack view to adjust itself when one or two views are hidden. My issue is exactly as described in below questions except that my stack view is inside table cell. The solution mentioned in these threads don't work for me. See screenshot below for the exact problem.

Stack view is pinned to all sides and distribution is fill equally.

How do we make it work?

UIStackView shift content to left when inner views are hidden

UIStackView Distribution Fill Equally

enter image description here

Constraints Storyboard func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "tableCellID", for: indexPath) as? TableViewCell else {
        fatalError("Can't find cell")
    }

    let profile = array[indexPath.row]

    if profile.status {
        cell.view2.isHidden = false
    } else {
        cell.stackViewTrailing.constant += cell.view2.frame.size.width
        cell.view2.isHidden = true
    }

    return cell
}
1
Show your TableViewCell class. This is actually really easy with autolayout. - Rakesha Shastri
I've uploaded storyboard screenshot. - Davis
What is the stack view trailing set to? - Rakesha Shastri
It's set to superview it is contained in. - Davis
Is that view's anchors set to the contentView's anchors. - Rakesha Shastri

1 Answers

0
votes

Your problem is that you're always adding some value to your trailing constant (cell.view2.frame.size.width) and never subtract it again (in the code you posted). Table view cells are being reused / recycled. So when you scroll and an old table view cell that scrolled out of the view and had only 2 arranged subviews is being resued but this time with 3 arranged subviews, it still has this extra constant you set for your stackViewTrailing constraint.

Try setting an absolute value for your constraint's constant rather that adding a value to it using the += operator, i.e. instead of

cell.stackViewTrailing.constant += cell.view2.frame.size.width

do this:

cell.stackViewTrailing.constant = cell.view2.frame.size.width + padding

That should solve the problem. (That is, if I understand your problem correctly.)

Note:

You might reconsider if a stack view is the right choice here. Stack views always adjust their arranged subviews' widths when one of them is hidden (or revealed) so that the remaining visible one take up all the available space. If you want to have 3 fixed columns no matter how many of them are visible, it might be a better idea to just use plain constraints and give all three subviews equal width constraints.