Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 502
user2588945 Avatar asked Sep 13 '13 11:09

user2588945


People also ask

How do I change cell height in Swift?

To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we'll need to make use of automatic dimension property.

What is tableView?

A table view displays a single column of vertically scrolling content, divided into rows and sections. Each row of a table displays a single piece of information related to your app. Sections let you group related rows together. For example, the Contacts app uses a table to display the names of the user's contacts.


1 Answers

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;
}
like image 60
wattson12 Avatar answered Nov 02 '22 22:11

wattson12