Kyu*_*Kyu 4 uiscrollview nstimer swift
帮我.我试图用UIScrollView制作NSTimer.但是在UIScroll View滚动期间NSTimer停止..
如何在滚动期间保持工作NSTimer?
vac*_*ama 27
我创建了一个简单的项目,其中包含一个scrollView和一个用NSTimer.更新的标签.使用时创建计时器scheduledTimerWithInterval,滚动时计时器不会运行.
解决的办法是与创建计时器NSTimer:timeInterval:target:selector:userInfo:repeats,然后调用addTimer上NSRunLoop.mainRunLoop()使用mode NSRunLoopCommonModes.这允许计时器在滚动时更新.
它正在运行:
这是我的演示代码:
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)"
}
}
Run Code Online (Sandbox Code Playgroud)
let timer = Timer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
Run Code Online (Sandbox Code Playgroud)