Friday, 24 June 2016

Dynamic row height of UITableViewCell

There may be situation where we want a UITableViewCell to be of dynamic height .

For example: We have a custom UITableViewCell in which we have a title UILabel and detail UILabel . We want detail UILabel  to be of dynamic height .

So first of all create a custom UITableViewCell class. And two UILabel named title and detail .

1) Set the top, leading and trailing constraint for title label to content view of cell .

2) Now set bottom , leading and trailing constraint for  detail label to content view of cell .

3) Set the vertical spacing  between title label and detail UILabel .

4) Now to prioritize  the title 's constraint over detail label 's constraint  set the content hugging and content compression priority .

  On title label set the content hugging and content compression priority to 751.

Again on detail label set the content hugging and content compression priority to 750 .


It is not yet done. Here we created a basic cell with two UILabel . To make it work in your view controller  set the estimated height for row at indexpath and height for row at indexpath  . UITableview provide methods for both purpose . You can return estimatedRowHeight as per your requirement. It is just an arbitrary value . Return the UITableViewAutomaticDimension for height for row at index path .

That's it .

No comments:

Post a Comment