Why does my UITableView “jump” when inserting or removing a row?

后端 未结 10 1171
小蘑菇
小蘑菇 2020-12-05 10:21

(Happy to accept an answer in Swift or Objective-C)

My table view has a few sections, and when a button is pressed, I want to insert a row at the end of section 0.

10条回答
  •  抹茶落季
    2020-12-05 10:21

    @GaétanZ's solution did not work for me (IOS12) but he's concept is right..

    SO I did the next logical step:

    IF table content does not know how tall is the cell THEN lets just “keep on scrolling" down RIGHT AFTER inserting the cell

    private func insertBottomBubble(withCompletionHandler completion: (() -> Void)?) {
        let bottomIndexPath = IndexPath(row: cbModelViewController!.viewModelsCount - 1, section: 0)
    
    
        CATransaction.begin()
        CATransaction.setAnimationDuration(0.9)
        CATransaction.setCompletionBlock {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                self.scrollToBottom(withCompletionHandler: completion)
            }
        }
        tableView.insertRows(at: [bottomIndexPath], with: isLeft == true ? .left : .right)
        self.scrollToBottom(withCompletionHandler: nil) // no jump, keep it down :D
        CATransaction.commit()
    }
    
    
    func scrollToBottom(withCompletionHandler completion: (() -> Void)?) {
        let bottomMessageIndexPath = IndexPath(row: tableView.numberOfRows(inSection: 0) - 1, section: 0)
        UIView.animate(withDuration: 0.45,
                       delay: TimeInterval(0),
                       options: UIView.AnimationOptions.curveEaseInOut,
                       animations: {
                        self.tableView.scrollToRow(at: bottomMessageIndexPath, at: .bottom, animated: false)
        },
                       completion: { success in
                        if success {
                            completion?()
                        }
    
        })
    

    iOS 12 tested only

提交回复
热议问题