简体   繁体   中英

iOS Calculate Height For Cell

I have a problem with Apple's dynamic resizing cells such that the logic for the layout of my cells isn't as cut and dry as just a few stacked growing UILabels.

As a result, I can't really use the dynamic resizing option they've provided and so I need to manually calculate the height of my cell using NSString boundingRect methods.

That's fine - it works, but I end up needing to store a lot of constants that keep track of my auto layout constraints. I feel like this is counter intuitive to what auto layout is supposed to do for me, so I'm not sure if this is the correct way to implement heightForRowAtIndexPath.

I essentially have to go and copy my constraints into a constant and then use those values in a class method to generate my heights. Apple provides very little internal insight into how UITableViewAutomaticDimension works, but it's clear that the height of the cell is still calculated BEFORE it is laid out. Thus I can't really add any complex logic to it unless I know what methods are called before.

Any ideas on what I should do, or if my approach is ok?

The common solution I can offer is to add a height constraint fro your cell and change the constraint according to your needs, whatever they are. UITableViewAutomaticDimension will resize cell to the height you specify with this constraint automatically.

If your table cell is custom then its easier if you use a method like configureCell and pass the indexPath to it from cellForRowAtIndexPath and then determine the layout based on the data that you have and see where you want the left and right label to be placed. Once you have done this store the height required in the model or perhaps another array that has the same number of rows as your table and use it to return in heightForRowAtIndexPath .

This is easier and gives you flexibility without having to fiddle with too many delegate methods of table view. Centralise your layout logic in one place. Another alternative is to override layoutSubviews of the table view cell and calculate the height there and store it.

If you want your tableview cell to be assigned a default height, you can use estimatedHeightForRowAtIndexPath: available in UITableViewDelegate. As per Apple guidelines:

// Use the estimatedHeight methods to quickly calcuate guessed values which will allow for fast load times of the table. // If these methods are implemented, the above -tableView:heightForXXX calls will be deferred until views are ready to be displayed, so more expensive logic can be placed there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM