(Swift)NSTimer 滚动时停止

(Swift) NSTimer Stop when Scrolling

帮帮我。 我试图用 UIScrollView 制作 NSTimer。但 在 UIScroll 视图上滚动时 NSTimer 停止..

如何在滚动期间保持 NSTimer 工作?

我创建了一个简单的项目,其中包含一个滚动视图和一个用 NSTimer 更新的标签。使用 scheduledTimerWithInterval 创建计时器时,滚动时计时器不会 运行。

解决方案是使用 NSTimer:timeInterval:target:selector:userInfo:repeats 创建计时器,然后使用 mode NSRunLoopCommonModesNSRunLoop.mainRunLoop() 上调用 addTimer。这允许计时器在滚动时更新。

这里是运行宁:

这是我的演示代码:

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)