views:

377

answers:

2

I am using a custom UITableViewCell, which has some labels. There is one label in the cell where the string length is variable, due to this i cannot set a constant height to the cell in heightForRowAtIndexPath method. Neither I want to place the calculation logic out of my custom cell into the table delegate.

+4  A: 

-heightForRowAtIndexPath: is where you get to set it. I know putting that logic in the tableview delegate is sort of ugly, but it can't be done in the cell.

Think about it, the tableview has to know the height of the cell before it even instantiates the cell so it can calculate the length of the scroll bar (which is proportional). That means you cannot calculate the size of the cell in the cell itself because the size of the cell has to be known well in advance of the cell ever being instantiated.

In other words, you can't set the row height in the cell because the tableview needs to know the height of cells it will never instantiate if the user doesn't scroll to them.

Louis Gerbarg
+1  A: 

How about defining a class method on your cell class to do the calculations? You might still have to pass a bunch of information from the delegate to the cell class (like a model object, or some contents), and you might have to duplicate some code from your cell's layoutSubviews or drawRect:, but at least all of the logic would live within the cell class.

Within your delegate, you can then factor out any logic you need to turn an index path into the cell class into its own method, callable from both heightForRowAtIndexPath: and cellForRowAtIndexPath:.

Sixten Otto
this seems to be a nice idea, thanks!
Konstantin