Iphone - when to calculate heightForRowAtIndexPath for a tableview when each cell height is dynamic?

前端 未结 10 1303
迷失自我
迷失自我 2020-11-30 19:50

I have seen this question asked many times but astoundingly, I have not seen a consistent answer, so I will give it a try myself:

If you have a tableview containing

10条回答
  •  暖寄归人
    2020-11-30 20:10

    An approach I have used in the past is to create a class variable to hold a single instance of the cell you are going to be using in the table (I call it a prototype cell). Then in the custom cell class I have a method to populate the data and determine the height the cell needs to be. Note that it can be a simpler variant of the method to really populate the data - instead of actually resizing a UILabel in a cell for example, it can just use the NSString height methods to determine how tall the UILabel would be in the final cell and then use the total cell height (plus a border on the bottom) and UILabel placement to determine the real height. YOu use the prototype cell just to get an idea of where elements are placed so you know what it means when a label is going to be 44 units high.

    In heightForRow: I then call that method to return the height.

    In cellForRow: I use the method that actually populates labels and resizes them (you never resize the UITableView cell yourself).

    If you want to get fancy, you can also cache the height for each cell based on the data you pass in (for instance it could just be on one NSString if that's all that determines height). If you have a lot of data that's often the same it may make sense to have a permanent cache instead of just in-memory.

    You can also try estimating line count based on character or word count, but in my experience that never works - and when it goes wrong it usually messes up a cell and all the cells below it.

提交回复
热议问题