![](/img/trans.png)
[英]How to Initialize UIViews and UIViewControllers Using Protocols in Swift
[英]How to display a timer in different UIViewControllers in Swift?
我想在應用程序的不同視圖控制器中顯示一個計時器(分鍾和秒)。 我怎樣才能做到這一點 ?
我當時想將計時器與Singleton一起使用,但是如何每秒鍾更新一次正確的標簽?
是的,您可以使用單例
此代碼調用方法updateLabel:
對象
NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateLabel:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
迅速
var myTimer: NSTimer? = nil
override func viewDidAppear(animated: Bool) {
myTimer = NSTimer(timeInterval: 1.0, target: self, selector: #selector(MyClass.updateAmazing),
userInfo: nil, repeats: true)
}
func updateAmazing() {
//update
}
在單例中,您應該啟動計時器,在控制器上,您開始更新標簽,並從單例中獲取值。
重要
別忘了使計時器失效。
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
myTimer.invalidate()
}
最簡單的方法-使用Singleton中的NSNotificationCenter或在更新計時器時可以創建帶有委托和調用方法的數組,該數組中的所有ViewController都會接收消息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.