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;
}
}
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With