Jerky Scrolling After Updating UITableViewCell in place with UITableViewAutomaticDimension

前端 未结 6 562
我在风中等你
我在风中等你 2020-12-04 05:49

I am building an app that has a feed view for user-submitted posts. This view has a UITableView with a custom UITableViewCell implementation. Insid

6条回答
  •  抹茶落季
    2020-12-04 06:17

    Following @dosdos answer.

    I also found interesting to implement: tableView(tableView: didEndDisplayingCell: forRowAtIndexPath:

    Specially for my code, where the cell is changing Constraints dynamically while the cell is already displayed on screen. Updating the Dictionary like this helps the second time the cell is displayed.

    var heightAtIndexPath = [NSIndexPath : NSNumber]()
    
    ....
    
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = UITableViewAutomaticDimension
    
    ....
    
    extension TableViewViewController: UITableViewDelegate {
    
        //MARK: - UITableViewDelegate
    
        func tableView(tableView: UITableView,
                       estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    
            let height = heightAtIndexPath[indexPath]
    
            if let height = height {
    
                return CGFloat(height)
            }
            else {
    
                return UITableViewAutomaticDimension
            }
        }
    
        func tableView(tableView: UITableView,
                       willDisplayCell cell: UITableViewCell,
                                       forRowAtIndexPath indexPath: NSIndexPath) {
    
            let height: NSNumber = CGRectGetHeight(cell.frame)
            heightAtIndexPath[indexPath] = height
        }
    
        func tableView(tableView: UITableView,
                       didEndDisplayingCell cell: UITableViewCell,
                                            forRowAtIndexPath indexPath: NSIndexPath) {
    
            let height: NSNumber = CGRectGetHeight(cell.frame)
            heightAtIndexPath[indexPath] = height
        }
    }
    

提交回复
热议问题