Search code examples
iphoneobjective-cipaduitableview

Different UITableViewCell heights


I have built three different cells in my storyboard and hooked all the outlets up, each cell has a unique identifier.

For example I have one cell which holds a picture, another which has a label and another with other contents, so they are all unique and each cell type requires its own height (dynamic or status, it doesn't matter).

However, how is it that I can make a cell with 'indentifier1' return a certain height and then the others cells returns different heights?

I know I can use - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath but I am unsure how to differentiate the cells.

I am using core data and fetch results for the tableview from that.

Edit

I have tried this with tags but its crashes at the first if statement:

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

    if ([[tableView cellForRowAtIndexPath:indexPath] tag] == 1) cellHeight = 170;
    else if ([[tableView cellForRowAtIndexPath:indexPath] tag] == 2) cellHeight = 100;
    else if ([[tableView cellForRowAtIndexPath:indexPath] tag] == 3) cellHeight = 140;

    return cellHeight;
}

Solution

  • of course it crashed, because you are in a delegate method, (you are a delegate of the UITableView) and from such method calling back the UITableView methods takes very high risk of crash.

    the method ([tableView cellForRowAtIndexPath:indexPath]), what you call, will call a delegate method again for the cell's height, and it causes an infinite loop, aka crash.

    this is normal behaviour.

    the key is in your original data source, you could store the height for each row in the original data source, and you can read everything back from there, in your delegate methods without any risk.

    your code fragment does not say where your data source is and what kind of your data source is, thus I cannot give more exact solution in lack of it, but the idea would be that.