IOS: dynamic height with a custom uitableviewcell

后端 未结 3 1821
攒了一身酷
攒了一身酷 2020-12-30 09:29

I am new at ios development and this is my problem thus far. I am able to dynamically calculate the height of a custom cell via the delegate \"heightForRowAtIndexPath\". S

相关标签:
3条回答
  • 2020-12-30 09:56

    There is a good tutorial that walks you through the process of determining the height that is required to fit your text and sizing the cell height appropriately.

    the tutorial is available here: http://www.raddonline.com/blogs/geek-journal/iphone-sdk-resizing-a-uitableviewcell-to-hold-variable-amounts-of-text/

    I have not attempted the methods in the tutorial myself, but it looks to be pretty thorough.

    Hope this helps!

    0 讨论(0)
  • 2020-12-30 10:11

    If the text in the cells is going to change, you will need to a call reloadData on your tableView when it does, otherwise the tableView:heightForRowAtIndexPath: won't be called.

    The way the tableView works is that it gathers the heights for all rows at every reload (and the reload variants). This is how iOS knows the height of the entire table. It doesn't call tableView:heightForRowAtIndexPath: again when grabbing individual cells. Usually calling reloadData is quite quick and this method, unlike its variants, doesn't cause any scrolling.

    See stackoverflow question and answer for useful background.

    Problems arise if you have to do a lot of work to calculate heights and you have hundreds or thousands of rows. In one use case I have like this, I cache the row height calculations to get decent performance. But if that's not your case, just be a little more liberal with reloadData.

    0 讨论(0)
  • 2020-12-30 10:12

    Your tableView:heightForRowAtIndexPath: seems correct, but you might want to check the following about the labelDescription cell label in your XIB file:

    • must match the width used in the tableView:heightForRowAtIndexPath: method (in your case, 320)
    • must match the font and size used in the tableView:heightForRowAtIndexPath: method (in your case "Arial" size 15)
    • set the label's "Adjust to fit" checkbox to NO
    • set the # of lines property to 0 (that way it allows the text to span multiple lines)

    If you suspect the tableView:heightForRowAtIndexPath: method does not get called after you scroll, you can easily verify that by adding a temporary NSLog statement in that method. If it never gets called, you might have forgotten to set your view controller as the UITableView's UITableViewDelegate delegate.

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