[英]Creating multiple Countdown Timers in Swift
好的,所以我試圖在一個標簽中添加一個2秒的倒數計時器,只要用戶雙擊屏幕就會激活。 因此,在雙擊時,用戶將找到用數字“2”創建的新標簽,然后是第二個“1”,然后是“0”。
我只需1個計時器即可完美實現。 當用戶雙擊以創建第二個或更多計時器時,應用程序崩潰。
我發現這是由於在類中而不是在函數中聲明變量,以允許計時器函數檢索此類聲明作為標簽。 如果我找到一種方法使計時器功能在另一個函數內而不是在類下面,它將正常工作。
所以這里的代碼僅在部署1個計時器時才有效。
在班級下:
var BTTimer = NSTimer ()
var BTCounter = 2
let BT = SKLabelNode
在功能觸摸下開始:
let B = SKSpriteNode(imageNamed: "B 110.png")
let Touch : UITouch! = touches.first
let TouchLocation = Touch.locationInNode(self)
let PreviousTouchLocation = Touch.previousLocationInNode(self)
let Player = childNodeWithName("Player") as! SKSpriteNode
let xPos = Player.position.x + (TouchLocation.x - PreviousTouchLocation.x)
let yPos = Player.position.y + (TouchLocation.y - PreviousTouchLocation.y)
B.position = CGPointMake(xPos, yPos)
B.zPosition = -2
self.addChild(B)
BT.fontSize = 27;
BT.fontColor = UIColor.redColor()
BT.position = CGPointMake(xPos - 9, yPos - 30)
BT.zPosition = -1
self.addChild(BT)
BT.text = String(BTCounter);
BTTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: #selector(GameScene.updateBCounter), userInfo: nil, repeats: true)
}
}
現在在同一個類的另一個函數下:
func updateBCounter() {
if(BTCounter > 0) {
BTCounter-=1
BT.text = String(BTCounter)
}
else if(BTCounter == 0) {
//Remove B
//Place C
}
我希望改變這一點,以便用戶能夠生成他希望部署的盡可能多的計時器。
您可以像這樣更新updateBCounter:
func updateBCounter(timer: NSTimer)
您的選擇器更改為#selector(GameScene.updateBCounter(_:)
在計划計時器時,可以將userInfo
設置為任何字典,發送到updateBCounter的計時器將在其userInfo
屬性中設置它。
我不確切地知道你想要做什么,但是這些是同時調用同一個選擇器的多個計時器的工具,但知道你正在處理哪一個。
擺脫跟蹤事物的屬性,並在userInfo字典中創建密鑰。
你可以使用任何對象作為userInfo(而不僅僅是字典),所以你也可以這樣做:
class TimerData {
var counter: Int
var l: SKLabelNode
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.