views:

241

answers:

2

I need to access my cell in the table from tableView:heightForRowAtIndexPath: since I want to use the data I have ion the custome cell for the height calculations. The only way I have found to get my cells is to call tableView:cellForRowAtIndexPath:

The problem with that is that calling tableView:cellForRowAtIndexPath: is actually creating the cells and than doing nothing with them. when the same cell will need to be used for drawing purpose it will be created again. So for the same index the cell is created twice.

So I am wondering is there a more effective way to do it. Thanks for the help.

+2  A: 

You don't have access to the cell in this method because it does not exist yet. tableView:heightForRowAtIndexPath: is called before you create the cell in tableView:cellForRowAtIndexPath:.

But it should not matter because you should not hold model information in the cell objects. The cells are only views and you should always hold the all the data you need to construct a cell in your model.

Ole Begemann
That's a noble thought, but it doesn't work if you need to use layoutSubviews to layout the cells in the proper format. In this case the height of the cell can be dynamically adjusted based on the generated cell content. This could still be worked around if you knew the width of your cells, but what if that is variable too? I'm running into this problem, and I haven't found a solution yet. Anyone?
JoBu1324
There is no way around it: with UITableView, you need to know the cell height before the cell is created.
Ole Begemann
I don't think that's true. I've noticed that tableView:heightFOrRowAtIndexPath: gets called before *and* after layoutSubviews. The problem I'm running into is a crash the first time I try to get the cell height; tableView:cellForRowAtIndexPath: causes a crash. I've tried putting the message in a try/catch block, but it doesn't do any good.
JoBu1324
Ok, I was wrong. tableView:heightForRowAtIndexPath crashes before or after tableView:cellForRowAtIndexPath: is called when you try to call tableView:cellForRowAtIndexPath: in it. I can calculate the row heights during the first run though; I wonder if there's a notification after the table is drawn on the screen so I can reload the cells with the correct height?
JoBu1324
I did find a solution, and it's works with system: UITableView has a property called "bounds" that does have the correct width. That and layoutSubviews allowed me to get the proper height for the cells, and it works when the device orientation changes.
JoBu1324
A: 

Typically, you choose which cell to return from tableView:cellForRowAtIndexPath: based on your data and the index path.
Thus, you can use that same data and index path to determine which cell height to return in tableView:heightForRowAtIndexPath:.

gerry3