简体   繁体   中英

How to get the dynamic cell height that is calculated by iOS auto layout?

I created a simply UITableViewController with dynamic cell height using multi-line UILabel. I let iOS auto layout does the calculation for me. So I didn't have to calculate any height myself. But now, I want to take whatever height iOS auto layout returns to me and increment it by N. I'm not sure how to go about doing it without reinventing the wheel in tableView(_:heightForRowAtIndexPath:) .

You can use this:

CGRect frame = [tableView rectForRowAtIndexPath:indexPath];
NSLog(@"row height : %f", frame.size.height);

so:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    CGRect frame = cell.frame;
    CGFLoat heightOfRow = frame.size.height;
    return heightOfRow +n;

}

EDIT:

It seems you can't do anything with the height until the table is setup, and the only way to solve this problem is to let the table load and then reload it with the new heights...can do it like this:

-(void)viewDidLayoutSubviews{
     [super viewDidLayoutSubviews];
     UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
     CGRect frame = cell.frame;
     self.heightOfRow = frame.size.height;
     [self.tableView reloadData];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

{

    return self.heightOfRow +n;

}

You may need to stick a BOOL in this so it only does it once.

I will update my answer with code.

Please find the code below to be used in iOS8

self.tableView.estimatedRowHeight = 100;
self.tableView.rowHeight = UITableViewAutomaticDimension;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM