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?
Best Answer
Swift 5 and 4.2 solution without KVO, DispatchQueue, or setting constraints yourself.
This solution is based on Gulz's answer.
1) Create a subclass of
UITableView
:2) Add a
UITableView
to your layout and set constraints on all sides. Set the class of it toContentSizedTableView
.3) You should see some errors, because Storyboard doesn't take our subclass'
intrinsicContentSize
into account. Fix this by opening the size inspector and overriding the intrinsicContentSize to a placeholder value. This is an override for design time. At runtime it will use the override in ourContentSizedTableView
classUpdate: Changed code for Swift 4.2. If you're using a prior version, use
UIViewNoIntrinsicMetric
instead ofUIView.noIntrinsicMetric