Jacobo Koenig
Jacobo Koenig

Reputation: 12534

UITableView with dynamic height for both the table and its cells

I am trying to create a non-scrollable tableview that adjusts its size based on its content.

However, I am able to do one of two things. Either:

  1. I define a set height for cells and calculate total height - tableViewHeightConstraint.constant = CGFloat(tasks.count*120)
  2. I calculate each cell's height individually based on its content, but I am not able to add them all up since not all cells are instantiated and ready for me to add their heights.

Any idea of how I can go about accomplishing this?

Upvotes: 1

Views: 41

Answers (1)

Rajesh
Rajesh

Reputation: 10434

You can observe the changes in the contentsize as this.

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"]) {

        CGSize newSize = [[change objectForKey:NSKeyValueChangeNewKey] CGSizeValue];
        CGSize oldSize = [[change objectForKey:NSKeyValueChangeOldKey] CGSizeValue];

        if (newSize.height != oldSize.height) {

            // use newSize.height for your process
        }
    }
}

make sure observer is removed

- (void)dealloc {
    if(self.isViewLoaded) {
        [self.tableView removeObserver:self forKeyPath:@"contentSize"];
    }
}

Upvotes: 1

Related Questions