Saturday, November 19, 2016

Swift 3 UITableView Dynamic cell height based on content

Let’s take an example of chat application, where chat bubbles dimensions vary dynamically based on the chatted text.



We can achieve this dynamic size of cell by calculating size of cell based on displaying text font, size and length.This is very tedious. We can achieve this simply using autolayouts and UITableView automatic dimension setting for row height.

First, Take your label and give below constraints. Constraint constants can be of your choice.

  1. top
  2. leading
  3. trailing &
  4. bottom




After that make label as multiline by giving number of Lines as 0 and Line Break as 'Word Wrap'.

Lines - 0
Line Break - Word Wrap






In the code, give the below settings to UITableView.


  
        self.tableViewRank.estimatedRowHeight = 500
      self.tableViewRank.rowHeight = UITableViewAutomaticDimension


That’s it. Now, Table view’s cells will be of dynamic height based on the label’s content.





Hope this post is useful. Feel free to comment incase of any queries.

No comments:

Post a Comment