user2588945 user2588945 - 7 days ago 5
iOS Question

How to dynamically set the height of a UITableView?

I have a tableview with different cell heights using the

heightForRowAtIndexPath:
method.

I would like to dynamically set the height of a
UITableView
. At the moment I'm setting the dimensions of the tableView in
viewDidLoad
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:
self.tableView.contentSize.height;
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;
}
else
{
return 200;
}
}

Answer

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;
}
Comments