Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic height of UITableViewCell using UIStackView

For much to many hours I have been struggling to get dynamic row height calculation for UITableViewCells running.

A StackView (pinned to the margins of the UITableViewCells contentView) should allow me to control the height of the cell by manipulating the hidden property of the Views inside the StackView (much like shown here: https://stackoverflow.com/a/36250618/606730)

I have added the mandatory settings for dynamic height in the viewContoller like this:

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

I did not override heightForRowAtIndexPath as this is where I want auto layout to do the magic.

My problem is that while the tableView is first loaded or the tableview is scrolling the cells are not seized correctly. But when I press inside a cell the height calculation does work and all the cells are shown in their correct height.

I have overridden setSelected of the UITableViewCell like this:

-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [UIView setAnimationsEnabled:NO];
    [super setSelected:selected animated:animated];
    self.viewInsideStackView.hidden = !selected;
    [UIView setAnimationsEnabled:YES];
}

This gets called as the tableview loads or scrolls for each cell. Manipulating self.viewInsideStackView.hidden should make the stack view recalculate it's height. But this does not work. I also tried calling layoutIfRequired but still the wrong size appears until I press a cell.

like image 421
Jakob Avatar asked Nov 08 '22 09:11

Jakob


1 Answers

try setting the spacing value for your stack view to something other than 0. I believe this will help iOS correctly calculate the height of your cells, making the tableview work

like image 67
RyanYue Avatar answered Nov 14 '22 22:11

RyanYue