Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Height Issue for UITableView Cells (Swift)

Text data of variable length are being injected into tableview cell labels. In order for each cell height to be properly sized, I have implemented in viewDidLoad():

self.tableView.estimatedRowHeight = 88.0 self.tableView.rowHeight = UITableViewAutomaticDimension 

This estimates the height to be 88.0 pixels and should resize the height automatically if larger. It works perfectly for cells that have yet to be scrolled to (as UITableViewAutomaticDimention is called upon scrolling to the cell), but not for the cells that are initially rendered onscreen upon loading the table with data.

I have tried reloading the data (as suggested in many other resources):

self.tableView.reloadData() 

in both viewDidAppear() and viewWillAppear() and it did not help. I am lost.. does anyone know how to render the dynamic height for the cells loaded initially on screen?

like image 365
simplexity Avatar asked May 27 '15 23:05

simplexity


People also ask

How do I change the dynamic height of a cell in Swift?

To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we'll need to make use of automatic dimension property.

How can I get UITableView height?

Use contentSize. height property of UITableView . I think you want to set the whole tableview with content size and then set the scrollview size related content of UITableView and for this use bellow code... After add data or reloadData in UITableView just set bellow code..

What is UITableView in Swift?

A view that presents data using rows in a single column. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+


1 Answers

Try This:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {     return UITableViewAutomaticDimension } 

EDIT

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {     return UITableViewAutomaticDimension } 

Swift 4

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {     return UITableViewAutomaticDimension } 

Swift 4.2

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {     return UITableView.automaticDimension } 

Define above Both Methods.
It solves the problem.

PS: Top and bottom constraints is required for this to work.

Here is example

like image 113
iDhaval Avatar answered Oct 16 '22 22:10

iDhaval