NSButton值作为swift中的默认值
我是swift的新手,使用Xcode尝试编写一个小的清单应用程序。我选中/取消选中复选框并退出应用程序后,下次重新打开应用程序时,状态将消失。我想知道如何将NSButton的当前状态保存为默认状态,以便下次打开应用程序时,它将显示与我关闭应用程序时相同的状态。我尝试了以下练习: 设置默认值:NSButton值作为swift中的默认值,swift,xcode,nsbutton,Swift,Xcode,Nsbutton,我是swift的新手,使用Xcode尝试编写一个小的清单应用程序。我选中/取消选中复选框并退出应用程序后,下次重新打开应用程序时,状态将消失。我想知道如何将NSButton的当前状态保存为默认状态,以便下次打开应用程序时,它将显示与我关闭应用程序时相同的状态。我尝试了以下练习: 设置默认值: @IBAction func Check1(_ sender: NSButton) { UserDefaults.standard.set(Check1.state, forKey:"Che
@IBAction func Check1(_ sender: NSButton) {
UserDefaults.standard.set(Check1.state, forKey:"Check1status")
}
override var representedObject: Any? {
didSet {
Check1.state = UserDefaults.standard.bool(forKey:"Check1status")
}
}
读取默认值:
@IBAction func Check1(_ sender: NSButton) {
UserDefaults.standard.set(Check1.state, forKey:"Check1status")
}
override var representedObject: Any? {
didSet {
Check1.state = UserDefaults.standard.bool(forKey:"Check1status")
}
}
但是,我收到了错误消息:“无法将'Bool'类型的值分配给'NSControl.StateValue'类型”
如何修复此错误?谢谢。因为
状态
不是布尔值。在Objective-C中,它是一个整数。在Swift中,它是一个rawValue
为整数的函数。另外,不要在representedObject.didSet
中设置状态。在viewDidLoad
中执行此操作:
override func viewDidLoad() {
super.viewDidLoad()
// When your app launches for the very first time on the user computer, set it to On
UserDefaults.standard.register(defaults: [
"Check1Status": NSControl.StateValue.on.rawValue
])
let state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"Check1status"))
check1.state = state
}
@IBAction func check1(_ sender: NSButton) {
// Swift performs do some background magic if you type check1.state
// Adding rawValue make it clear that you are writing an integer to the UserDefaults
UserDefaults.standard.set(check1.state.rawValue, forKey:"Check1status")
}
因为
状态
不是布尔值。在Objective-C中,它是一个整数。在Swift中,它是一个rawValue
为整数的函数。另外,不要在representedObject.didSet
中设置状态。在viewDidLoad
中执行此操作:
override func viewDidLoad() {
super.viewDidLoad()
// When your app launches for the very first time on the user computer, set it to On
UserDefaults.standard.register(defaults: [
"Check1Status": NSControl.StateValue.on.rawValue
])
let state = NSControl.StateValue(UserDefaults.standard.integer(forKey:"Check1status"))
check1.state = state
}
@IBAction func check1(_ sender: NSButton) {
// Swift performs do some background magic if you type check1.state
// Adding rawValue make it clear that you are writing an integer to the UserDefaults
UserDefaults.standard.set(check1.state.rawValue, forKey:"Check1status")
}
查看UserDefaults。根据你的问题更清楚地勾选这一项。我在尝试使用SelfKey.isSelected时收到错误消息:“类型为'NSButton'的值没有成员'isSelected'”。我应该在NSButton中使用另一个成员吗?isSelected==true的可能重复项是state==nsonstateCheckout UserDefaults。根据你的问题更清楚地勾选这一项。我在尝试使用SelfKey.isSelected时收到错误消息:“类型为'NSButton'的值没有成员'isSelected'”。我应该在NSButton中使用另一个成员吗?isSelected==true的可能副本是state==NSOnState