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

标签 ios swift uislider uiswitch

<分区>

我想在 View Controller 之间切换后保存 UISwitch 的状态。任何帮助将不胜感激!

我有一个带有 UISwitch 的第一个 View Controller ,用于控制不同 View Controller 中的背景音乐:

@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()
        }
     }

还有第二个 View Controller ,用于在开关打开或关闭时在后台加载或不加载音乐:

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

我还有一节音乐课:

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

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

还有关于如何在 Slider 中应用的想法吗?

如有任何帮助,我们将不胜感激!

谢谢

最佳答案

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

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

关于ios - 如何在 SWIFT 4 中保存 UISwitch 的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47213956/

相关文章:

iphone - 如何在 iOS 的一个证书中分发两个应用程序?

ios - 在动态 UITableViewCell 的顶部添加一个单元格

ios - 如何使用约束修复此 View

swift - 当之前在设备上授权 healthkit 访问时工作正常,但否则会崩溃

iphone - UISlider的editingDidEnd事件在iPad上不起作用

php - 我希望在单击按钮时将我的 UISlider 值发送到 mysql 数据库

ios - iPhone-在 PickerView 中设置字体列表

iphone - 改变状态栏高度的iPhone Activity有哪些?

ios - 设置内容高度后无法更新 UITextView 大小

ios - UISlider 边界和框架宽度返回不正确的值