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?
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)"
}
}
let timer = Timer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
let timer = Timer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoop.Mode.common)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With