【问题标题】:swift. UserDefaults and UISwitch迅速。 UserDefaults 和 UISwitch
【发布时间】:2021-02-26 12:38:14
【问题描述】:

我正在尝试让 UserDefaults 与 UISwitch 一起使用,但是当我强制关闭应用并重新打开它时,开关状态没有保存。

更新:让它工作。即使应用关闭,开关状态也会保持在“开”或“关”状态。

我的代码:

let defaults = UserDefaults.standard


@IBAction func switchAction(_ sender: UISwitch) {
    
    defaults.set(true, forKey: "saveTrue")
    defaults.set(false, forKey: "saveFalse")

    if sender.isOn == false {
        sender.setOn(defaults.bool(forKey: "saveFalse"), animated: true)
    } else if sender.isOn == true {
        sender.setOn(defaults.bool(forKey: "saveTrue"), animated: true)
    }

}

回答:;;;

let defaults = UserDefaults.standard

override func viewDidLoad() {
    super.viewDidLoad()

    if let switchValue = getSwitchValue(), switchValue {
        switchOutlet.setOn(true, animated: true)
    } else {
        switchOutlet.setOn(false, animated: true)
    }
}


@IBAction func Switch(_ sender: UISwitch) {
if sender.isOn == false {
        setSwitchStatus(status: false)
        sender.setOn(false, animated: true)
    } else if sender.isOn == true {
        setSwitchStatus(status: true)
        sender.setOn(true, animated: true)
    }
}


func setSwitchStatus(status: Bool?) {
    if status != nil {
        defaults.set(status, forKey: "save1")
    }
}

func getSwitchValue() -> Bool? {
    return defaults.bool(forKey: "save1")
}

【问题讨论】:

  • 我不明白你在做什么。您的 sender.setOn 代码不会改变任何内容。当 setOn = false 已经是 false 时,您正在设置它。
  • 离题但不是比较真假,你可以只做if sender.isOn {...} else {...}或使用三元运算符
  • 我使用 .isOn 来设置真或假。 .setOn 使开关处于 ON 或 OFF 状态。我的目标是使用 UserDrfaults 将 UISwitch 的状态保存在内存中。因此,如果在 UISwitch 处于 On 状态时关闭了应用程序,则在重新打开应用程序时它将保持这种状态。

标签: swift nsuserdefaults uiswitch


【解决方案1】:

我不确定这就是你要找的东西,但我会这样做:

let defaults = UserDefaults.standard
@IBOutlet mySwitch: UISwitch!

//or any other function that is called 'when the app is reopened' 
override func viewDidAppear() {
    self.mySwitch.setOn(defaults.bool(forKey: "switchDefaultsKey"), animated: true)
}

@IBAction func switchAction(_ sender: UISwitch) {
    defaults.set(sender.isOn, forKey: "switchDefaultsKey")
}

【讨论】:

  • 我已经解决了问题。在最初的问题正文中说明了这一点。同样在 viewDidAppear 函数中,“defaults.setOn”将不起作用
猜你喜欢
  • 2018-10-25
  • 1970-01-01
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
  • 2014-07-28
  • 2015-03-12
  • 1970-01-01
  • 2020-09-30
相关资源
最近更新 更多