iOS 8 Auto height cell not correct height at first load

前端 未结 5 1518
遥遥无期
遥遥无期 2020-12-28 15:54

I have an iOS 8 application where I have a search results page that each cell is autosized based on the height of a certain label. However, after the view first loads the c

相关标签:
5条回答
  • 2020-12-28 16:03

    The answer from rdelmar did not work for me.

    What I have done is added this code:

    [tableView setNeedsLayout];
    [tableView layoutIfNeeded];
    [tableView reloadData];
    

    after data is fetched and first [tableView reloadData] is called, which in my case is located in viewDidLoad method of my View Controller.

    So result code would be:

    NSArray *fetchedData = ...
    
    [tableView reloadData]; //Fist table reload
    [tableView setNeedsLayout];
    [tableView layoutIfNeeded];
    [tableView reloadData]; //Second table reload
    

    This answer is taken from here: http://useyourloaf.com/blog/self-sizing-table-view-cells.html#comment-1783719287

    0 讨论(0)
  • 2020-12-28 16:06

    I had the same problem and fixed it by moving assignments to the cell's UILabels' text properties (being the only components that could influence the height calculation in my particular cell) to:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    instead of:

    -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

    Before doing this I noticed that the cell height would be correctly calculated if a cell was scrolled momentarily off-screen and then back into view. Most likely because, at that point, the cell had the necessary information regarding the UILabel content determining the final height.

    0 讨论(0)
  • 2020-12-28 16:19

    I think instead of forcing a tableView.reloadData() and tableView.layoutIfNeeded() in viewDidLoad, you can just set your tableView's auto height in viewWillLayoutSubviews():

    Swift:

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        tableView.estimatedRowHeight = 300
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    
    0 讨论(0)
  • 2020-12-28 16:22

    I was able to go around this one by not using nibs/storyboards but rather have the layout done programmatically.

    0 讨论(0)
  • 2020-12-28 16:23

    Yes, I've seen this same problem when making the views and constraints in the storyboard (but not with code added views). Iv'e fixed this by adding this code in the custom cell class,

    -(void)didMoveToSuperview { 
        [self layoutIfNeeded];
    }
    

    This could probably go other places, but this method seems to be called only once, so I thought it was a good place to do it.

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