Reputation: 124
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
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