Settings.bundle Swift 5
Settings.bundle Swift 5
我正在使用 swift 5 中的 settings.bundle 并希望观察默认设置的变化并更新应用程序而不重新启动它 - 执行此操作的最佳方法是什么?
UserDefaults.standard.register(defaults: ["String" : "Any"])
let defaultValues1 = ["btn1_name": "Name your Btn 1"]
UserDefaults.standard.register(defaults: defaultValues1)
let btn1value = ["btn1_onoff": true]
UserDefaults.standard.register(defaults: btn1value)
let defaultValues2 = ["btn2_name": "Name your Btn 2"]
UserDefaults.standard.register(defaults: defaultValues2)
let btn2value = ["btn2_onoff": true]
UserDefaults.standard.register(defaults: btn2value)
将此添加到 ViewController:
NotificationCenter.default.addObserver(self, selector: #selector(settingChanged(notification:)), name: UserDefaults.didChangeNotification, object: nil)
}
然后使用以下内容创建一个@objc 函数:
@objc func settingChanged(notification: NSNotification) {
let userDefaults = UserDefaults.standard
let btn1settings = userDefaults.bool(forKey: "btn1_onoff")
if !btn1settings {
btn1.isHidden = true
btn1_label.isHidden = true
btn1_count.isHidden = true
}
else {
btn1.isHidden = false
btn1_label.isHidden = false
btn1_count.isHidden = false
}
let btn1name = userDefaults.string(forKey: "btn1_name")
btn1_label.text = btn1name
这将在“应用程序设置”中更新设置时更新应用程序
我正在使用 swift 5 中的 settings.bundle 并希望观察默认设置的变化并更新应用程序而不重新启动它 - 执行此操作的最佳方法是什么?
UserDefaults.standard.register(defaults: ["String" : "Any"])
let defaultValues1 = ["btn1_name": "Name your Btn 1"]
UserDefaults.standard.register(defaults: defaultValues1)
let btn1value = ["btn1_onoff": true]
UserDefaults.standard.register(defaults: btn1value)
let defaultValues2 = ["btn2_name": "Name your Btn 2"]
UserDefaults.standard.register(defaults: defaultValues2)
let btn2value = ["btn2_onoff": true]
UserDefaults.standard.register(defaults: btn2value)
将此添加到 ViewController:
NotificationCenter.default.addObserver(self, selector: #selector(settingChanged(notification:)), name: UserDefaults.didChangeNotification, object: nil)
}
然后使用以下内容创建一个@objc 函数:
@objc func settingChanged(notification: NSNotification) {
let userDefaults = UserDefaults.standard
let btn1settings = userDefaults.bool(forKey: "btn1_onoff")
if !btn1settings {
btn1.isHidden = true
btn1_label.isHidden = true
btn1_count.isHidden = true
}
else {
btn1.isHidden = false
btn1_label.isHidden = false
btn1_count.isHidden = false
}
let btn1name = userDefaults.string(forKey: "btn1_name")
btn1_label.text = btn1name
这将在“应用程序设置”中更新设置时更新应用程序