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?
You can try Out this Custom
AGTableView
To Set a TableView Height Constraint Using storyboard or programmatically. (This class automatically fetch a height constraint and set content view height to yourtableview height).
Note If any problem to set a Height then
yourTableView.layoutSubviews()
.I had a table view inside scroll view and had to calculate tableView's height and resize it accordingly. Those are steps I've taken:
0) add a UIView to your scrollView (probably will work without this step but i did it to avoid any possible conflicts) - this will be a containr view for your table view. If you take this step , then set the views borders right to tableview's ones.
1) create a subclass of UITableView:
2) set class of a table view in Storyboard to IntrinsicTableView: screenshot: http://joxi.ru/a2XEENpsyBWq0A
3) Set the heightConstraint to your table view
4) drag the IBoutlet of your table to your ViewController
5) drag the IBoutlet of your table's height constraint to your ViewController
6) add this method into your ViewController:
Hope this helps
As an extension of Anooj VM's answer, I suggest the following to refresh content size only when it changes.
This approach also disable scrolling properly and support larger lists and rotation. There is no need to dispatch_async because contentSize changes are dispatched on main thread.
Swift Solution
Follow these steps:
1- Set the height constraint for the table from the storyboard.
2- Drag the height constraint from the storyboard and create @IBOutlet for it in the view controller file.
3- Then you can change the height for the table dynamicaly using this code:
Update
If the last row is cut for you, try to call viewWillLayoutSubviews() in willDisplay cell function:
I've tried this in iOS 7 and it worked for me
Actually I found the answer myself.
I just create a new
CGRect
for thetableView.frame
with theheight
oftable.contentSize.height
That sets the height of the
UITableView
to theheight
of its content. Since the code modifies the UI, do not forget to run it in the main thread: