UITableview Scrolls to Top on Reload

后端 未结 5 1307
不知归路
不知归路 2020-12-28 18:23

I am facing problem in my app - you can post and edit your favorite places. After posting a post, or editing a specific post (UITableViewCell), UITablevie

5条回答
  •  遥遥无期
    2020-12-28 18:42

    Igor's answer is correct if you are using dynamically resizable cells (UITableViewAutomaticDimension)

    Here it is in swift 3:

        private var cellHeights: [IndexPath: CGFloat?] = [:]
        var expandedIndexPaths: [IndexPath] = []
    
        func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            cellHeights[indexPath] = cell.frame.height
        }
    
        func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
            if let height = cellHeights[indexPath] {
                return height ?? UITableViewAutomaticDimension
            }
            return UITableViewAutomaticDimension
        }
    
    
        func expandCell(cell: UITableViewCell) {
          if let indexPath = tableView.indexPath(for: cell) {
            if !expandedIndexPaths.contains(indexPath) {
                expandedIndexPaths.append(indexPath)
                cellHeights[indexPath] = nil
                tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
                //tableView.scrollToRow(at: indexPath, at: .top, animated: true)
            }
          }
        }
    

提交回复
热议问题