I am creating an app which will have a question in a UILabel
and a multiple choice answers displayed in UITableView
, each row showing a multiple choice. Questions and answers will vary, so I need this UITableView
to be dynamic in height.
I would like to find a sizeToFit
work around for the table. Where the table's frame is set to the height of all it's content.
Can anyone advise on how I can achieve this?
objc version of Musa almatri
In case where your contentSize is not right this is because it is based on the estimatedRowHeight (automatic), use this before
source : https://forums.developer.apple.com/thread/81895
Swift 3, iOS 10.3
Solution 1: Just put
self.tableview.sizeToFit()
incellForRowAt indexPath
function. Make sure to set tableview height higher then you need. This is a good solution if you don't have views below tableview. However, if you have, bottom tableview constraint will not be updated (I didn't try to fix it because I came up with solution 2)Example:
Solution 2: Set tableview height constraint in storyboard and drag it to the ViewController. If you know the average height of your cell and you know how many elements your array contains, you can do something like this:
*EDIT:
After all the solutions I tried and every of them was fixing something, but not completely, this is the answer that explains and fixes this problem completely.
Mu solution for this in swift 3: Call this method in
viewDidAppear
There is a much better way to do it if you use AutoLayout: change the constraint that determines the height. Just calculate the height of your table contents, then find the constraint and change it. Here's an example (assuming that the constraint that determines your table's height is actually a height constraint with relation "Equal"):
In case you don't want to track table view's content size changes yourself, you might find this subclass useful.