UITableView ContentSize when using dynamic height on UITableViewCells

I searched for this for many hours, but did not find a way to do this.

I have a UITableView for which UITableViewCells using AutomaticDimension for Height:

 tableView.RowHeight = UITableView.AutomaticDimension; tableView.EstimatedRowHeight = 160f; 

The problem is that I am trying to get the tableView ContentSize . It seems to be calculated based on EstimatedRowHeight instead of the current height of its rows. Suppose if there are 10 cells, then the return value of ContentSize is 160x10.

Then my question is, is there a way to do this.

Any help would be really appreciated ... I am using Xamarin.iOS, but Obj-C and Swift answers are certainly welcome :)

+5
source share
3 answers

I think that @Daniel J's answer only works because of how the animation completion handler is planned - at first glance, there is no guarantee that the table will reload before the animation finishes.

I think the best solution (in Swift, as this is what I used): -

 func reloadAndResizeTable() { self.tableView.reloadData() dispatch_async(dispatch_get_main_queue()) { self.tableHeightConstraint.constant = self.tableView.contentSize.height UIView.animateWithDuration(0.4) { self.view.layoutIfNeeded() } } } 

I actually used animation delay due to the effect I wanted, but it also works with a duration of zero. I call this function every time I update the contents of the table, and it enlivens and resizes if necessary.

+9
source

I had a script in which I also needed to know ContentSize in order to set a frame in a non-full-screen tableView that had different cell counts of different heights. Then I would configure tableView (via NSLayoutConstraint) as the height of this content.

The following worked, although I feel a little hacked:

Setting up all the code in 'viewDidLoad'
Set rowHeight to automatic
Set the estimated value of RowHeight to more than I expected when the cell will ever be (in this case I did not expect the cell to ever be higher than about 60 points, so set the score to 120)
Wrap the reload of the tableView in the animation block, and then request contentSize and follow the appropriate steps in the completion block

 - (void)viewDidLoad { [super viewDidLoad]; self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.estimatedRowHeight = 120.0; [UIView animateWithDuration:0 animations:^{ [self.tableView reloadData]; } completion:^(BOOL finished) { self.tableViewHeight.constant = self.tableView.contentSize.height; [self.view layoutIfNeeded]; }]; } 
+7
source
 self.coins = coins tableView.reloadData() view.layoutIfNeeded() tableViewHeightConstraint.constant = tableView.contentSize.height view.layoutIfNeeded() 

worked without UITableViewAutomaticDimension and ratedRowHeight. iOS 11

0
source

Source: https://habr.com/ru/post/1242229/


All Articles