UITableView dynamic cell heights only correct after some scrolling

后端 未结 24 1296
误落风尘
误落风尘 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:26

    None of the above solutions worked but the following combination of the suggestions did.

    Had to add the following in viewDidLoad().

    DispatchQueue.main.async {
    
            self.tableView.reloadData()
    
            self.tableView.setNeedsLayout()
            self.tableView.layoutIfNeeded()
    
            self.tableView.reloadData()
    
        }
    

    The above combination of reloadData, setNeedsLayout and layoutIfNeeded worked but not any other. Could be specific to the cells in the project though. And yes, had to invoke reloadData twice to make it work.

    Also set the following in viewDidLoad

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = MyEstimatedHeight
    

    In tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

    cell.setNeedsLayout()
    cell.layoutIfNeeded() 
    

提交回复
热议问题