I have a UIStackView
where it can show a label, image, table view or nothing based on user selection. Here is my current hierarchy for the dynamic view:
When I call UIStackView_Child.addArrangedSubview(...)
with a label or image it works perfectly, but addArrangedSubview(tableView)
does not show the table. I have tableView.scrollEnabled = false
and set frame to fixed height based on number of cell and defined the table's cellHeight
.
Any help would be much appreciated, thanks!
Another way to do this without explicitly setting the frame height and width is to embed your table view inside an empty view, pin the table view to the top, bottom, left and right and set a "greater than or equal to" constraint to the table view's height.
That's because stackview tries to compress content as much as possible. When you initally add a tableview, I'm assuming it has no content, so stackview compresses the width to 0 because it has nothing to show. You have to do one of two things:
After the table gets populated with data, you have to set the tableView's frame. I do this by calculating how big each cell is going to be. I know the width is going to be as big as the view that contains stackview. So it winds up being something like
let estimatedHeight = tableView.numberOfRows(inSection: 0) //You may need to modify as necessary
let width = parentView.frame.size.width
tableView.frame = CGRect(x: 0, y: 0, width: width, height: estimatedHeight)
Once you set the tableView's frame, stackview should automatically adjust.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With