问题描述
帮帮我.我试图用 UIScrollView 制作 NSTimer.但NSTimer 在 UIScroll View 滚动期间停止..
Help me.I tried to make NSTimer with UIScrollView. butNSTimer stop during Scrolling on UIScroll View..
如何在滚动期间保持 NSTimer 工作?
How can I keep work NSTimer during scrolling?
推荐答案
我创建了一个简单的项目,其中包含一个滚动视图和一个使用 NSTimer
更新的标签.使用 scheduledTimerWithInterval
创建计时器时,滚动时计时器不运行.
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.
解决方案是用NSTimer:timeInterval:target:selector:userInfo:repeats
创建定时器,然后在NSRunLoop.mainRunLoop()addTimer
/code> 与 mode
NSRunLoopCommonModes
.这允许计时器在滚动时更新.
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.
它正在运行:
这是我的演示代码:
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)"
}
}
斯威夫特 3:
let timer = Timer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
斯威夫特 4、5:
let timer = Timer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoop.Mode.common)
这篇关于(Swift) NSTimer 滚动时停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!