SirRupertIII
SirRupertIII

Reputation: 12596

Calculate custom UITableViewCell height at "indexPath" from -tableView:cellForRowAtIndexPath:?

I adjust the height of a custom UITableViewCell inside the custom class, and I believe I need to use the -tableView:cellForRowAtIndexPath: method to adjust the height of the cell. I am attempting to just adjust the height of the custom cell in the custom cell class, then grab the cell at the given index path cast it, and return the height of that cell like this:

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
 {
     CustomUITableViewCell *cell = (CustomUITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];

     return cell.frame.size.height;
 }

But I am getting stack overflow. What is a better way around doing this?

Upvotes: 1

Views: 1247

Answers (2)

Timothy Moose
Timothy Moose

Reputation: 9915

If it's a storyboard cell, you can call dequeueReusableCellWithIdentifier:. Otherwise, you can just instantiate the cell directly with something like [CustomUITableViewCell alloc] initWithFrame:].

I use this approach (using a prototype cell to calculate height) myself because it allows our designer to modify storyboard cells without requiring code changes.

You may want to adjust your approach based on whether the height is static or dynamic as discussed here.

Upvotes: 0

Mundi
Mundi

Reputation: 80273

The table view delegate will first call heightForRowAtIndexPath: and then the datasource will construct the cell in cellForRowAtIndexPath: after that based on the computed information.

Therefore your approach will not work.

You need to have some logic for computing the height. (E.g. if you are displaying text the height might be dynamic and depend on the amount of text - you could calculate that with an NSString method.)

If you are just displaying a few types of cells with fixed heights, simply define these heights as constants and return the correct height based on the same logic you have in cellForRowAtIndexPath: to decide which cell to use.

#define kBasicCellHeight 50
#define kAdvancedCellHeight 100

- (CGFloat)tableView:(UITableView *)tableView 
       heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (needToUseBasicCellAtThisIndexPath) {
       return kBasicCellHeight;
    }
    return kAdvancedCellHeight;         
}

Upvotes: 2

Related Questions