如何在Spritekit中实现切换开/关按钮?

时间:2018-05-15 17:10:12

标签: swift sprite-kit

我正在尝试实现切换开/关按钮。问题是,如果我多次触摸该位置,该应用程序会冻结。有没有办法实现切换按钮?

// 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")
    }
}

1 个答案:

答案 0 :(得分:1)

我正在做的两个假设是你在touchesBegan中调用这个代码,而photoToggle是在场景级别设置的Bool。

Apple建议您每次更改值时都不要调用defaults.synchronize(),而是自动完成

此代码用作切换,并且不会冻结。

private var photoToggle = false
触摸开始

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")
}