I have been trying to develop an app which contains self sizing Table View Cells. I've looked a lot into tutorials and online documentation and came across these two lines of code:
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = UITableViewAutomaticDimension (and tried with 44 here also)
The cells would work as following:
The user can write something and choose whether to upload or not an image. The cell would resize according to whether there is in fact an image or not and also according to the text size.
My problems are:
UIImageView
that holds the image is also on a fixed size and the image is set on aspect to fit (I could not come up with a better solution);UIImageView
?It's quite easy actually. You have to set all constraints from top to bottom, but don't set any height constraints.
My advice is to start with a simple layout to see how it works. For example: create just a UITextView
with number of lines set to 0
. For that example you need just 4 constraints:
•V:|-0-[textView]
(from text view to superview top)
•V:[textView]-0-|
(from text view to superview bottom
•Horizontal constrains (left and right) to superview
If you manage to get it working, add the UIImageView
. Remember that you have all vertical constraints from top to bottom.
V:|-0-[textView]-0-[image]-0-|
Don't set height constraints anywhere - the height will be inferred automatically from intrinsicContentSize
method.
Now that I explained how to do it, I'm going to tell you not to do it :) The performance will probably be terrible - forget about 60 FPS, especially if you have paging - if you load next 20 cells, it'll have to calculate 20 heights and it takes a lot of time => stuttering. I'm talking from experience here. Forget about UITableViewAutomaticDimension
and calculate everything manually - it's not that hard.
But what about AutoLayout? Is it really so slow as I was talking about? Probably you will be surprised but it’s truth. Incredibly slow if you want see perfect smooth scrolling in your app on all actual devices which have long lifecycle (especially compared to Android devices). And more subviews you have, less quickly AutoLayout works.