Tom B.
Tom B.

Reputation: 124

How to implement toggle on/off button in Spritekit?

I am trying to implement toggle on / off button. The issue is that if I touch the location multiple times, the app freezes. Is there a way to implement toggle button?

// Disabled / Enabled Photo
if (photoSwitch?.contains(location))! {
    Sound.play(file: "switch", fileExtension: "mp3", numberOfLoops: 0)
    if photoToggle == true {
        UserDefaults.standard.set(true, forKey: "photoSwitch")
        defaults.synchronize()
        photoToggle = false
        photoOn?.alpha = 1
        photoOff?.alpha = 0
        print("on")
    } else if photoToggle == false {
        UserDefaults.standard.set(false, forKey: "photoSwitch")
        defaults.synchronize()
        photoToggle = true
        photoOn?.alpha = 0
        photoOff?.alpha = 1
        print("off")
    }
}

Upvotes: 0

Views: 228

Answers (1)

Ron Myschuk
Ron Myschuk

Reputation: 6061

2 assumptions I am making is that you are calling this code in your touchesBegan, and that photoToggle is a Bool set at the scene level.

Apple recommends not calling defaults.synchronize() every time you change a value, it is done automatically

this code works as a toggle, and doesn't freeze.

private var photoToggle = false

in touches began

if photoSwitch?.contains(location) {

    Sound.play(file: "switch", fileExtension: "mp3", numberOfLoops: 0)

    UserDefaults.standard.set(!photoToggle , forKey: "photoSwitch")

    photoToggle = !photoToggle
    photoOn?.isHidden = photoToggle 
    photoOff?.isHidden = !photoToggle
    print(photoToggle ? "on" : "off")
}

Upvotes: 1

Related Questions