Setting variable UITableViewCell height

后端 未结 2 1983
面向向阳花
面向向阳花 2021-01-14 20:10

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

相关标签:
2条回答
  • 2021-01-14 21:06

    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:.

    0 讨论(0)
  • 2021-01-14 21:07

    -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.

    0 讨论(0)
提交回复
热议问题