Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView content size while using auto-layout

I want to calculate Content size of my UITableView. I am using autolayout with height UITableViewAutomaticDimension.

Tried to get [UITableView contentsize] after reloading tableview, in that case height get calculated based on estimatedRowHeight.

self.tableView.estimatedRowHeight = 50; self.tableView.rowHeight = UITableViewAutomaticDimension; 

Delegate -

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{     return UITableViewAutomaticDimension; } 

Trying to get content size and assign it to height constrain.

[self.tableView reloadData]; [self.tableView layoutIfNeeded]; self.tableHeightConstraint.constant = self.tableView.contentSize.height; 

Any suggestions? Thanks in advance.

Edit:

Finally I am solved my problem with some tweak. I changed tableview height to max (In my case 300 is max) before reloading data on table, so tableview has space to resize all cells.

self.tableHeightConstraint.constant = 300; [self.tableView reloadData]; [self.tableView layoutIfNeeded]; self.tableHeightConstraint.constant = self.tableView.contentSize.height; 

Thanks for help.

like image 790
OnkarK Avatar asked Mar 15 '16 04:03

OnkarK


2 Answers

Finally I am solved my problem with some tweak. I changed tableview height to max (Objective-C: CGFLOAT_MAX, Swift: CGFloat.greatestFiniteMagnitude) before reloading data on table, so tableview has space to resize all cells.

Objective-C:

self.tableHeightConstraint.constant = CGFLOAT_MAX; [self.tableView reloadData]; [self.tableView layoutIfNeeded]; self.tableHeightConstraint.constant = self.tableView.contentSize.height; 

Swift:

tableHeightConstraint.constant = CGFloat.greatestFiniteMagnitude tableView.reloadData() tableView.layoutIfNeeded() tableHeightConstraint.constant = contentTableView.contentSize.height 

Posting this so it will be helpful for others.

like image 82
OnkarK Avatar answered Oct 11 '22 09:10

OnkarK


Finally, I understood you problem and here is the solution of it.

I hope you have already done this.

  1. First take put some fix height of UITableView.
  2. Then take the constraint IBOutlet of UITableView Height.
  3. Then under viewDidLayoutSubviews method you can get the original UITableView height after populating the data.

Update the below code:

override func viewDidLayoutSubviews() {     constTableViewHeight.constant = tableView.contentSize.height } 

Update:

self.tableView.estimatedRowHeight = UITableViewAutomaticDimension; 

Please check this.

like image 31
Sohil R. Memon Avatar answered Oct 11 '22 09:10

Sohil R. Memon