HeroAlom
HeroAlom

Reputation: 21

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

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?

Upvotes: 0

Views: 103

Answers (1)

Vladislav Markov
Vladislav Markov

Reputation: 587

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

Upvotes: 1

Related Questions