[英]Swift how to prevent multiple NSTimer.scheduledTimerWithTimeInterval
[英]How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift?
我正在開發一款游戲,我想創建一個暫停菜單。 這是我的代碼:
self.view?.paused = true
但是NSTimer.scheduledTimerWithTimeInterval
仍在運行......
for var i=0; i < rocketCount; i++ {
var a: NSTimeInterval = 1
ii += a
delaysShow = 2.0 + ((stimulus + interStimulus) * ii)
var time3 = NSTimer.scheduledTimerWithTimeInterval(delaysShow!, target: self, selector: Selector("showRocket:"), userInfo: rocketid[i], repeats: false)
}
我希望time3
在玩家點擊暫停菜單時暫停計時器並在玩家回到游戲時繼續運行計時器,但我怎么能暫停NSTimer.scheduledTimerWithTimeInterval
? 請幫幫我。
您需要使其無效並重新創建它。 然后,如果您有相同的按鈕可以暫停和恢復計時器,則可以使用isPaused
bool來跟蹤狀態:
var isPaused = true
var timer = NSTimer()
@IBAction func pauseResume(sender: AnyObject) {
if isPaused{
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("somAction"), userInfo: nil, repeats: true)
isPaused = false
} else {
timer.invalidate()
isPaused = true
}
}
阻止它
time3.invalidate()
再來一次
time3.fire()
開始:
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateView"), userInfo: nil, repeats: true)
恢復:
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateView"), userInfo: nil, repeats: true)
暫停:
timer.invalidate
這對我有用。 訣竅是不要尋找像"timer.resume"
或"timer.validate"
這樣的東西。 只需使用“相同的代碼啟動計時器”即可在暫停后恢復計時器 。
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
timer.invalidate()
time += 1
label.text = String(time)
'label'是輸出的計時器。
你無法恢復計時器。 而不是恢復 - 只需創建一個新的計時器。
class SomeClass : NSObject { // class must be NSObject, if there is no "NSObject" you'll get the error at runtime
var timer = NSTimer()
init() {
super.init()
startOrResumeTimer()
}
func timerAction() {
NSLog("timer action")
}
func pauseTimer() {
timer.invalidate
}
func startOrResumeTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("timerAction"), userInfo: nil, repeats: true)
}
}
SWIFT3
全球宣言:
var swiftTimer = Timer()
var count = 30
var timer = Timer()
@IBOutlet weak var CountDownTimer: UILabel!
viewDidLoad中
override func viewDidLoad() { super.viewDidLoad() BtnStart.tag = 0 }
觸發IBACTION:
@IBAction func BtnStartTapped(_ sender: Any) {
if BtnStart.tag == 0 {
BtnStart.setTitle("STOP", for: .normal)
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ScoreBoardVC.update), userInfo: nil, repeats: true)
BtnStart.tag = 1
} else {
BtnStart.setTitle("START", for: .normal)
timer.invalidate()
BtnStart.tag = 0
}
}
處理事物的功能:
func update(){
if(count > 0){
let minutes = String(count / 60)
let ConvMin = Float(minutes)
let minuttes1 = String(format: "%.0f", ConvMin!)
print(minutes)
let seconds = String(count % 60)
let ConvSec = Float(seconds)
let seconds1 = String(format: "%.0f", ConvSec!)
CountDownTimer.text = (minuttes1 + ":" + seconds1)
count += 1
}
}
我剛剛在游戲中遇到了類似的問題,並找到了一個簡單的解決方案。
首先我應該像其他人一樣指出,Timer和NSTimer沒有暫停功能。 您必須使用Timer.invalidate()停止Timer。 使定時器無效后,必須再次初始化它以啟動定時器。 引自https://developer.apple.com/documentation/foundation/timer ,函數.invalidate() -
停止計時器再次發射並請求從其運行循環中刪除它。
要暫停計時器,我們可以使用Timer.fireDate,這是Timer(和NSTimer)保存計時器將來觸發的日期的地方。
這是我們如何通過保存定時器剩余的秒數直到它再次觸發來暫停定時器。
//The variable we will store the remaining timers time in
var timeUntilFire = TimeInterval()
//The timer to pause
var gameTimer = Timer.scheduledTimer(timeInterval: delaysShow!, target: self, selector: #selector(GameClass.showRocket), userInfo: rocketid[i], repeats: false)
func pauseTimer()
{
//Get the difference in seconds between now and the future fire date
timeUntilFire = gameTimer.fireDate.timeIntervalSinceNow
//Stop the timer
gameTimer.invalidate()
}
func resumeTimer()
{
//Start the timer again with the previously invalidated timers time left with timeUntilFire
gameTimer = Timer.scheduledTimer(timeInterval: timeUntilFire, target: self, selector: #selector(GameClass.showRocket), userInfo: rocketid[i], repeats: false)
}
注意:在獲取fireDate之前,不要使Timer無效。 調用invalidate()后,Timer似乎將fireDate重置為2001-01-01 00:00:00 +0000。
第二個注意:計時器可能會在設置fireDate后觸發。 這將導致負數,這將默認Timer在0.1毫秒后運行。 https://developer.apple.com/documentation/foundation/timer/1412416-scheduledtimer
暫停計時器:timer.invalidate()
和
恢復計時器:重新創建計時器。 它的工作正常。
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(mainController.updateTimer), userInfo: nil, repeats: true)
盡管這里公開的解決方案很好,但我認為缺少一個重要的見解。 像這里解釋的很多人一樣,timer invalidate()和recreate是最好的選擇。 但有人可能會說你可以這樣做:
var paused:Bool
func timerAction() {
if !paused {
// Do stuff here
}
}
更容易實現,但效率會降低。
出於能源影響的原因,Apple會盡可能地避免使用計時器,並且更喜歡事件通知。 如果您確實需要使用計時器,則應通過使當前計時器無效來有效地實現暫停。 在Apple Energy Efficiency Guide中閱讀有關計時器的建議: https : //developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/MinimizeTimerUse.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.