Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Dynamically set UITableView height in Swift

Our UITableView exists on a ViewController (and not a TableViewController). We populate it at run time with two rows. When we set a height constraint the table appears fine. When we don't set the height constraint the table completely does not appear. How can you set the UITableView to dynamically set its height?

I've seen threads about dynamically setting the row height (which does work well) but not about the actual table height. There are a few threads on this specific point but none seem to work for me.


Update on solution: As Robotic Cat suggested we set up a height constraint on the UITableView in the Storyboard (we had that already) and then did Ctrl drag to create an IBOutlet in our controller. From there we executed the following code in viewWillAppear per Vignesh's answer:

tableViewHeightConstraint.constant = tableView.contentSize.height

Note before executing the above code we are calling reloadData() in the same method to populate our table.

like image 230
Marcus Leon Avatar asked Mar 14 '17 19:03

Marcus Leon


People also ask

How do I change cell height in Swift?

To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we'll need to make use of automatic dimension property. We'll see this with the help of an sample project.


2 Answers

We don't have automatic dimension for UITableView, they only affect the UITableViewCell height. If you want to set the table view height dynamically, I think the best way is to set the table view height constraint equal to its content size after the table view done loading. I mean something like,

tableViewHeightConstraint.constant = tableView.contentSize.height
like image 145
Vignesh Avatar answered Sep 28 '22 09:09

Vignesh


You can change tableView frame in multiple ways, with animations etc.

tableView.frame = CGRect(x: leftTableBorder, y: topTableBorder, width: tableWidth, height: tableHeight)

Or you can change tableView related constraints and then update constraints with layoutIfNeeded, also animated if you wish.

For example if you have a height constraint property:

tableViewHeightConstraint.constant = desiredHeight

layoutIfNeeded()

In any case, constraints are needed, so autolayout knows how to render the table.

like image 42
silentBob Avatar answered Sep 28 '22 09:09

silentBob