Dynamically resizing UITableViewCell again

Well, I've been searching a lot to solve my problem, however, I haven't found anything useful.

I have my custom cells, which can(or can't) contain images, text, titles, etc in free order, so I need to set the row's height depending on its content. Like these two: http://db.tt/AVBKYuEY http://db.tt/HbnXMMFn

The only way I can make them is by storyboard.

So, I call tableView:cellForRowAtIndex: and set there the whole contents and then I want to set the height of the row, BUT I can't do it, because the row's height is set in tableView:height...:, which is called BEFORE tableView:cellForRowAtIndex:

Btw, I also have constraints in my storyboard, so, it would be great if I could use them to count the cell height.

And also it perfectly changes width when I rotate iPhone, what is strange in fact that I can't change height

How to solve my problem?

Upvotes: 1

Views: 387

Answers (1)

rdelmar
rdelmar

Reputation: 104082

You can set the height in tableView:heightForRowAtIndexPath:. You have access in that method to the index path and therefore the index of the array supplying the data to the cell. So, you need to look at that data, and do any calculations that are needed to determine the cell height, and return that value.

After Edit: Here's an example of calculating height for a multi-line label. I create a temporary label, fill it with the text that this row will contain, and then use sizeWithFont:constrainedToSize:LineBreakMode: to do the calculation:

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UILabel *label = [[UILabel alloc] init];
    label.numberOfLines = 0; // allows label to have as many lines as needed
    label.text = _objects[indexPath.row][@"detail2"]; // this is the data I'm passing in the detail label
    CGSize labelSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(300, 300000) lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat h = labelSize.height;
    return h + 50; //50 is base height for my cell with only one line of text, determined empirically
}

Upvotes: 1

Related Questions