如何在 SWIFT 4 中保存 UISwitch 的状态?

Man*_*anu 5 uislider uiswitch ios swift

我想在视图控制器之间进行更改后保存 UISwitch 的状态。任何帮助将不胜感激!

我有一个带有 UISwitch 的第一个视图控制器,用于在不同的视图控制器中控制背景中的音乐:

@IBOutlet weak var SwitchMusic: UISwitch!
        let defaults = UserDefaults.standard
        var switchON : Bool = false

@IBAction func checkState(_ sender: UISwitch) {
        if (sender.isOn == true)
        {
            switchON = true
            defaults.set(switchON, forKey: "switchON")
            MusicHelper.sharedHelper.playBackgroundMusic()
        }
        if (sender.isOn == false)
        {
            switchON = false
            defaults.set(switchON, forKey: "switchON")
            MusicHelper.sharedHelper.stopBackgroundMusic()
        }
     }
Run Code Online (Sandbox Code Playgroud)

如果开关打开或关闭,第二个视图控制器在后台加载或不加载音乐:

override func viewDidLoad() {
        super.viewDidLoad()

        if defaults.value(forKey: "switchON") != nil{
            let switchON: Bool = defaults.value(forKey: "switchON")  as! Bool
            if switchON == true{
                MusicHelper.sharedHelper.playBackgroundMusic()
            }
            else if switchON == false{
                MusicHelper.sharedHelper.stopBackgroundMusic()
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我还有一堂音乐课:

class MusicHelper {

    let defaults = UserDefaults.standard

    static let sharedHelper = MusicHelper()

    var musicBackgroundIntro:AVAudioPlayer = AVAudioPlayer()
    func playBackgroundMusic() {
        do {
            let audioPath = Bundle.main.path(forResource: "Music", ofType: "mp3")
            try musicBackgroundIntro = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
            musicBackgroundIntro.numberOfLoops = -1
            musicBackgroundIntro.prepareToPlay()
            musicBackgroundIntro.play()
        } catch {
            print("Cannot play the file")
        }
    }
    func stopBackgroundMusic() {
        musicBackgroundIntro.stop()
    }
Run Code Online (Sandbox Code Playgroud)

}

现在它可以完美地播放视图控制器之间的背景音乐,并且可以关闭和打开......但不幸的是不保存 UISwitch 的当前状态,并且总是当我进入第一个视图控制器时的状态的开关打开。

还有什么想法也可以应用于 Slider 吗?

任何帮助将不胜感激!

谢谢

Rei*_*ica 0

对您来说最简单的方法是创建一个static var isSwitchOn: Bool = false

该状态将在来回转换之间保留。