4

As the title says, I have a custom UITableCell in which I have some UIStackViews. Each of those stacks contains many subviews but I just want to show three of them when the cell is displayed for the first time. If a user wants to see more, there is a [+] button that calls a method that adds the remaining.

The custom cell height is determined via UITableViewAutomaticDimension and it works perfectly for the first display of the cell but when I try to add and remove subviews to the stack, there are views that shouldn't be modified that lose they constraints and the ones that should be displayed doesn't do it in some cases. What I'd like is to show all the UILabels and the height of the cell to be updated.

The method that is called when the button [+] is pressed is the following:

@objc private func changeImage(sender: UIButton) {

    let index = (Int(sender.accessibilityValue!)!)
    let open : Bool = openItem[index]
    let plateStack : UIStackView = plateStacks[index]
    let plates : [UILabel] = platesViews[index]

    if !open {
       sender.setImage(UIImage(named: "less")?.withRenderingMode(.alwaysTemplate), for: .normal)
       let nPlatesToAdd = max(platesViews[index].count - 3, 0)
       for i in 0..<nPlatesToAdd {
            let plate = plates[i + 3]
            plateStack.addArrangedSubview(plate)
            plate.leadingAnchor.constraint(equalTo: plateStack.leadingAnchor, constant: 0).isActive = true
            plate.trailingAnchor.constraint(equalTo: plateStack.trailingAnchor, constant: 0).isActive = true
        }
    }
    else {
        sender.setImage(UIImage(named: "more")?.withRenderingMode(.alwaysTemplate), for: .normal)
        var i = plateStack.arrangedSubviews.count - 1
        while i > 2 {
            let view = plateStack.arrangedSubviews[i]
            plateStack.removeArrangedSubview(view)
            view.removeFromSuperview()
            i = i - 1
        }
    }
        openItem[index] = !open
}

The first display of the cell (everything's ok) and after click on the [+] button:

enter image description here

aashish tamsya
  • 4,903
  • 3
  • 23
  • 34
Pere Rumbo
  • 95
  • 1
  • 8

1 Answers1

5

It happened because tableView is already rendered its layout. You might need to check some causes :

  • make sure the stackView constraint is properly put to contentView
  • stackView's distribution must be fill
  • After you change something that affects tableView height, you can use these code to update cell height without reloading the table:

    tableView.beginUpdates()
    tableView.endUpdates()

Sowattana Sigen
  • 202
  • 2
  • 10
  • Thank you very much for your answer Sowattana. The third point solved it. I used it with a UIView.performWithoutAnimation() and a proper implementation of the prepareForReuse() of the custom cell. Now it works perfect! – Pere Rumbo Sep 21 '18 at 13:22