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

时间:2019-05-10 10:11:59

标签: swift uitableview smooth-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 个答案:

答案 0 :(得分:1)

我尝试了您的代码,它对我来说正常工作。但是:

  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()
    }