[英]NSButton value as default in swift
I am a newbie in swift using Xcode trying to write a small checklist app. 我是使用Xcode快速尝试编写一个小型清单应用程序的新手。 After I check/uncheck the checkbox and exit the app, the state just disappears next time when I reopen it next time.
选中/取消选中复选框并退出应用程序后,下次重新打开该状态时,下次将消失。 I am wondering how can I save the current state of NSButton as default so that next time when I open the app, it will show up the same state when I closed it.
我想知道如何将NSButton的当前状态保存为默认状态,以便下次打开应用程序时,它在关闭时会显示相同的状态。 I tried below practice:
我尝试了以下做法:
Set default value: 设置默认值:
@IBAction func Check1(_ sender: NSButton) {
UserDefaults.standard.set(Check1.state, forKey:"Check1status")
}
Read default value: 读取默认值:
override var representedObject: Any? {
didSet {
Check1.state = UserDefaults.standard.bool(forKey:"Check1status")
}
}
However I received error message:"Cannot assign value of type 'Bool' to type 'NSControl.StateValue'" 但是我收到错误消息:“无法将类型'Bool'的值分配给类型'NSControl.StateValue'”
How can I fix this error? 如何解决此错误? Thanks.
谢谢。
Because state
is not a boolean value. 因为
state
不是布尔值。 In Objective-C, it's an integer. 在Objective-C中,它是整数。 In Swift, it's a struct whose
rawValue
is an integer. 在Swift中,这是一个
rawValue
是整数的结构 。 Also, don't set the state in representedObject.didSet
. 此外,不要在设置状态
representedObject.didSet
。 Do it in viewDidLoad
: 在
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.