user2588945 user2588945 - 9 months ago 48
iOS Question

How to dynamically set the height of a UITableView?

I have a tableview with different cell heights using the


I would like to dynamically set the height of a
. At the moment I'm setting the dimensions of the tableView in
method using:

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 770, 310, 400)];
self.tableView.dataSource = self;
self.tableView.delegate = self;

I thought maybe I could add this:
but the problem of course is that the content size is only calculated after the table loads, so if I put it in

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 770, 310, self.tableView.contentSize.height)];

it doesn't work.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
NSString *description = [photosFromCommentsArray objectAtIndex:indexPath.row];
// NSLog(@"description is %@",description);

if(description == (id)[NSNull null])
return 70;
return 200;

Answer Source

Add an observer for the contentSize property on the table view, and adjust the frame accordingly

[self.tableView addObserver:self forKeyPath:@"contentSize" options:0 context:NULL];

then in the callback:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    CGRect frame = self.tableView.frame;
    frame.size = self.tableView.contentSize;
    self.tableView.frame = frame;