Search code examples
iosxcodeswifttimernstimer

Remove label after x seconds in swift


In my simple game(ping pong), I want to show a SKLabelnode on the screen when a point is made. This label has to stay for 1 second and after that it has to dissappear.

How do I do this?

PS: I can not use the "sleep" function because I want the other code keep running.


Solution

  • You can use an SKSequence to add and remove the label. A sequence does start the actions delayed after the one before has finished.

    var timeToWait:NSTimeInterval = 2.0
    
    //Wait a given amount of time. Here 2 seconds
    var waitAction = SKAction.waitForDuration(timeToWait)
    
    //Block to add your Label
    var addLabelBlock = SKAction.runBlock({
        addChild(yourLabel)
    })
    //Action to remove your label from the parent.
    var removeNodeAction = SKAction.removeFromParent()
    
    //Everything put in a sequence
    var addAndRemoveSequence = SKAction.sequence([addLabelBlock, waitAction, removeNodeAction])
    
    yourLabel.runAction(addAndRemoveSequence)