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

十年热恋 提交于 2019-12-08 09:12:37

问题


I spend lot of time to figure out this bug. in beginning scrolling looks good but time to time scrolling increasing automatic that is make unreadable for human. how to keep scrolling same as like as beginning.

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

Would you help me to fix this bug please or give any alternative solution for keep scrolling automatic?


回答1:


I try your code, and it works correctly for me. But:

  1. You can add animate option .curveLiner (animation will occurs evenly across the whole duration). May be it was your bug:

    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. You should invalidate timer when view disappears (differently view creates additional timer every time while old timers are working):

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


来源:https://stackoverflow.com/questions/56075451/how-to-uitableview-keep-scrolling-to-bottom-auto-scrolling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!