(Swift) NSTimer Stop when Scrolling [duplicate]

被刻印的时光 ゝ 提交于 2019-12-04 13:31:16

问题


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?


回答1:


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:

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)


来源:https://stackoverflow.com/questions/34234939/swift-nstimer-stop-when-scrolling

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