Search code examples
objective-cuitableviewcustom-cellsubviewsrow-height

Calculating dynamically the height of a custom UITableViewCell


I am building a application without the IB and I am writing everything from scratch. I have a custom UITableViewCell and when I try to calculate the height, it behaves like there are no subviews. I could find a lot of discussion about dynamically setting the height, but nothing really about how to calculate it, based on the subviews and how and where to set the constraints. What I did is setting constraints for my first component - UIImageView and add them the contenView of my cell. What I get is 0.

I will appreciate any input on that or at least direction!

heightForRowAtIndexPath:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [[UITableViewCell alloc]init];
    cell.imageView.image = [UIImage imageNamed:@"avatar"];

    cell.imageView.translatesAutoresizingMaskIntoConstraints=NO;

    NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-30-[image]" options:0 metrics:nil views:@{ @"image": cell.imageView }];

    [cell.contentView addConstraints:constraints];

    NSArray *constraints2 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[image]" options:0 metrics:nil views:@{ @"image": cell.imageView}];

    [cell.contentView addConstraints:constraints2];

    [ NSLayoutConstraint constraintWithItem:cell.imageView attribute: NSLayoutAttributeWidth
                                  relatedBy:NSLayoutRelationEqual toItem:cell.imageView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0f];

     CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    NSLog(@"%f",height);

    return height;

}

Solution

  • My solution for this kind of problem is UITableViewAutomaticDimension. You just return this in heightForRowAtIndexPath method. You will have to set tableView.estimatedRowHeight to some value that is close to what you will get.

    For instance, if you have 5 cells with height [100,200,250,270,300] you can set estimatedRowHeight to 220 (or something similar).

    You can take a look at first answer at Using Auto Layout in UITableView for dynamic cell layouts & variable row heights as well.