Pascal
Pascal

Reputation: 2700

UITableViewAutomaticDimension To fit subviews

My app has a table view with automatic sized row heights (UITableViewAutomaticDimension for heightForRow-Delegate-Function). My custom cells have subviews, that can have different sizes (they contain an always different number of bar charts).

However, automatic cell height does not work to fit these different sizes of the subview of the tableview cell.

It only works, if I set a constraint (e.g. make.top.equalTo(self).offset(300) with snap kit) for the subview in the tableview cell - but since these subviews can have different sizes, this is not a clean solution.

Do you know a better approach?

Thanks!

Upvotes: 1

Views: 451

Answers (1)

alegelos
alegelos

Reputation: 2604

First: on viewdidLoad (not in delegate):

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140 //this estimation will improve performance (can be omitted), set the +/- size of most cases.

Just don't override the cell height delegate.

Second: In your cell, u added that subView that contains chars. Add that subView constraints, but more important add a vertical spacing between that subview and the cell (this case the super view). Like the image.

enter image description here

If the subview height will set the cell height. Just make sure your chars inside the subView to set the subView height (with constraints).

For more details, here there's a good step by step.

Upvotes: 1

Related Questions