UITableView如何保持滚动到底部[自动滚动]?

How to UITableView keep Scrolling to bottom [Auto Scrolling]?

我花了很多时间来找出这个错误。在开始滚动 看起来不错,但不时滚动增加自动 人类不可读。如何保持滚动与开始时一样。

    var  start_index = 0
    var  dest_index  = 0  //approximately 300  
    var  timer       = Timer()
    var  falagisTrue : Bool?

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        dest_index = newsViewModels.count
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.keepScrolling), userInfo: nil, repeats: true)

    }



    @objc func keepScrolling(){
        if start_index > dest_index - 2{
            timer.invalidate()
        }else{
            if  (falagisTrue ?? false ||  falagisTrue == nil)  {
                falagisTrue = false
                start_index += 1

                UIView.animate(withDuration: 10, delay: 0, options: [], animations: {
                    let Index = IndexPath(row: self.start_index, section: 0)
                    self.tableView.scrollToRow(at:Index, at: .top, animated: false)
                }) { finished in
                    self.falagisTrue = true
                }
            }
        }
    }

你能帮我修复这个错误,或者提供任何替代解决方案来保持自动滚动吗?

我试过你的代码,它对我来说工作正常。但是:

  1. 您可以添加动画选项 .curveLiner(动画将在整个持续时间内均匀出现)。可能是你的错误:

    UIView.animate(withDuration: 10, delay: 0, options: [.curveLinear], animations: {
        let Index = IndexPath(row: self.start_index, section: 0)
        self.tableView.scrollToRow(at:Index, at: .top, animated: false)
    }) { finished in
        self.falagisTrue = true
    }
    
  2. 您应该在视图消失时使计时器无效(不同的视图每次都会在旧计时器工作时创建额外的计时器):

    override func viewWillDisappear(_ animated: Bool) {
        timer.invalidate()
    }