2

I'm trying to use a stackview inside a tableview cell. My stack view has two labels aligned horizontally. I've added a size class override in IB to align the labels vertically for compact width.

The alignment of the label does change as expected but the height of the cells is incorrect until I scroll cells out and back in.

My table view specifies to calculate the height of the cell using:

  // Automatic row height calculation
  tableView.rowHeight = UITableViewAutomaticDimension
  tableView.estimatedRowHeight = 68.0 // set to whatever your "average" cell height is

So, in an iPhone SE, I want the labels side by side in landscape but one on top of the other in portrait. If I start my app in portrait mode the labels are as expected but when I rotate to landscape they move to side by side but the cell still has the height as in portrait. If I scroll cells off the screen then the cell height is corrected.

What am I missing?

Please help.

Thanks.

Phantom59
  • 947
  • 1
  • 8
  • 19
  • I think I'm going to give up on trying to use stack views with size class in a tableview cell. I am able to achieve, pretty much, the same effect with "Vary for traits" in Xcode 8. This, basically, means that I install and uninstall constraints on my UI elements based on the size class. A stackview would have made this a lot easier; specifically, you can change labels from being horizontally to vertically aligned by just changing the alignment property instead of having to install and uninstall a handful of constraints. Stackviews are easy to adopt so I'll reconsider if I get some new info. – Phantom59 Mar 05 '17 at 16:27

1 Answers1

2

OK. Looks like there may be a legitimate bug but I continued to do some digging because stackviews are so much easier to work with. And, finally, got an answer in https://www.raywenderlich.com.

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  DispatchQueue.main.async {
    self.tableView.beginUpdates()
    self.tableView.endUpdates()
  }
}

Yeap!, wrapping begin/end update calls asynchronously in the main queue allows the cell's height to get properly calculated. Never would have thought of it since traitCollectionDidChange() is already running in the main queue.

See Using uistackviews in uitableviewcell for details.

Thanks, Jerry!

Phantom59
  • 947
  • 1
  • 8
  • 19