(Swift)滚动时NSTimer停止

时间:2015-12-12 00:53:55

标签: swift uiscrollview nstimer

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

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

1 个答案:

答案 0 :(得分:20)

我创建了一个带有scrollView的简单项目和一个用NSTimer更新的标签。使用scheduledTimerWithInterval创建计时器时,滚动时计时器不会运行。

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

这里正在运行:

Demo .gif

这是我的演示代码:

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)
相关问题