Jerky Scrolling After Updating UITableViewCell in place with UITableViewAutomaticDimension

前端 未结 6 564
我在风中等你
我在风中等你 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

    dosdos answer worked for me in Swift 2

    Declare the ivar

    var heightAtIndexPath = NSMutableDictionary()
    

    in func viewDidLoad()

    func viewDidLoad() {
      .... your code
      self.tableView.rowHeight = UITableViewAutomaticDimension
    }
    

    Then add the following 2 methods:

    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
       let height = self.heightAtIndexPath.objectForKey(indexPath)
       if ((height) != nil) {
         return CGFloat(height!.floatValue)
       } else {
        return UITableViewAutomaticDimension
       }
     }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
      let height = cell.frame.size.height
      self.heightAtIndexPath.setObject(height, forKey: indexPath)
    }
    

    SWIFT 3:

    var heightAtIndexPath = [IndexPath: CGFloat]()
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return self.heightAtIndexPath[indexPath] ?? UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        self.heightAtIndexPath[indexPath] = cell.frame.size.height
    }
    

提交回复
热议问题