UITableView dynamic cell heights only correct after some scrolling

后端 未结 24 1245
误落风尘
误落风尘 2020-11-29 16:41

I have a UITableView with a custom UITableViewCell defined in a storyboard using auto layout. The cell has several multiline UILabels.

相关标签:
24条回答
  • 2020-11-29 17:11

    In my case, the issue with the cell height takes place after the initial table view is loaded, and a user action takes place (tapping on a button in a cell that has an effect of changing the cell height). I have been unable to get the cell to change its height unless I do:

    [self.tableView reloadData];
    

    I did try

    [cell layoutIfNeeded];
    

    but that didn't work.

    0 讨论(0)
  • 2020-11-29 17:12

    none of the above solutions worked for me, what worked is this recipe of a magic: call them in this order:

    tableView.reloadData()
    tableView.layoutIfNeeded() tableView.beginUpdates() tableView.endUpdates()

    my tableView data are populated from a web service, in the call back of the connection I write the above lines.

    0 讨论(0)
  • 2020-11-29 17:14

    This worked for me when other similar solutions did not:

    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        layoutIfNeeded()
    }
    

    This seems like an actual bug since I am very familiar with AutoLayout and how to use UITableViewAutomaticDimension, however I still occasionally come across this issue. I'm glad I finally found something that works as a workaround.

    0 讨论(0)
  • 2020-11-29 17:14

    For iOS 12+ only, 2019 onwards...

    An ongoing example of Apple's occasional bizarre incompetence, where problems go on for literally years.

    It does seem to be the case that

            cell.layoutIfNeeded()
            return cell
    

    will fix it. (You're losing some performance of course.)

    Such is life with Apple.

    0 讨论(0)
  • 2020-11-29 17:15

    Adding [cell layoutIfNeeded] in cellForRowAtIndexPath does not work for cells that are initially scrolled out-of-view.

    Nor does prefacing it with [cell setNeedsLayout].

    You still have to scroll certain cells out and back into view for them to resize correctly.

    This is pretty frustrating since most devs have Dynamic Type, AutoLayout and Self-Sizing Cells working properly — except for this annoying case. This bug impacts all of my "taller" table view controllers.

    0 讨论(0)
  • 2020-11-29 17:18

    In my case the last line of the UILabel was truncated when the cell was displayed for the first time. It happened pretty randomly and the only way to size it correctly was to scroll the cell out of the view and to bring it back. I tried all the possible solutions displayed so far (layoutIfNeeded..reloadData) but nothing worked for me. The trick was to set "Autoshrink" to Minimuum Font Scale (0.5 for me). Give it a try

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