Search code examples
swiftuiscrollviewnstimer

(Swift) NSTimer Stop when Scrolling


Help me. I tried to make NSTimer with UIScrollView. but NSTimer stop during Scrolling on UIScroll View..

How can I keep work NSTimer during scrolling?


Solution

  • I created a simple project with a scrollView and a label that is updated with an NSTimer. When creating the timer with scheduledTimerWithInterval, the timer does not run when scrolling.

    The solution is to create the timer with NSTimer:timeInterval:target:selector:userInfo:repeats and then call addTimer on NSRunLoop.mainRunLoop() with mode NSRunLoopCommonModes. This allows the timer to update while scrolling.

    Here it is running:

    Demo .gif

    Here is my demo code:

    class ViewController: UIViewController {
    
        @IBOutlet weak var timerLabel: UILabel!
        var count = 0
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            timerLabel.text = "0"
    
            // This doesn't work when scrolling
            // let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
    
            // Do these two lines instead:
            let timer = NSTimer(timeInterval: 1, target: self, selector: "update", userInfo: nil, repeats: true)
    
            NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
        }
    
        func update() {
            count += 1
            timerLabel.text = "\(count)"
        }
    }
    

    Swift 3:

    let timer = Timer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
    RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
    

    Swift 4, 5:

    let timer = Timer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
    RunLoop.main.add(timer, forMode: RunLoop.Mode.common)