简体   繁体   中英

Removing an extra zero from a TimerLabel in SpriteKit Swift

I have created a timer function in swift SpriteKit and assigned it to a ScoreLabel. when the timer is active and updating itself, the undesired result is... 0:01 - 0:09 and then it is 0:010, I need to write some code to remove that second zero when the "second hand" changes from :09 to :10.

A little help would be great.

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   for touch: AnyObject in touches {




    if ScoreLabel.text == "0"{

    let actionrun = SKAction.runBlock({
       self.score++
        self.timesecond++
        if self.timesecond == 60 {self.timesecond = 0}
        self.ScoreLabel.text = "\(self.score/60):0\(self.timesecond)"


          })

   ScoreLabel.runAction(SKAction.repeatActionForever(SKAction.sequence([actionwait,actionrun])))

    }
self.ScoreLabel.text = String(format: "%d:%02d", self.score/60, self.timesecond)

Should do the trick!

%02d

Means that any number with less than two decimal digits will be zero padded.

var timeSecondString = String(format: "%02d", self.timesecond)
self.ScoreLabel.text = "\(self.score/60):\(self.timesecondString)"

I havent tested it but it should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM