我编写了一个昼夜按钮主题。如果用户按下日期按钮,GlobalData.DayBool = true
和 GlobalData.NightBool = false
。当他们按下夜间按钮时,GlobalData.DayBool = false
和 GlobalData.NightBool = true
。背景变为夜色或白色,具体取决于哪个是真还是假。
假设用户点击了夜间按钮。 GlobalData.NightBool = true
和 GlobalData.DayBool = false
,背景变为黑色。
我希望根据他们按下的按钮保存 bool 值,这样当他们关闭应用程序时,他们的背景将与他们选择的相同。
//Day Button Pressed
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if dayButton.containsPoint(location) {
for touch: AnyObject in touches {
_ = touch.locationInNode(self)
backgroundColor = GlobalData.dayColor
GlobalData.nightBool = false
GlobalData.dayBool = true
}
}
}
//Night Button Pressed
for touch: AnyObject in touches
let location = touch.locationInNode(self)
if nightButton.containsPoint(location) {
for touch: AnyObject in touches {
_ = touch.locationInNode(self)
backgroundColor = GlobalData.nightColor
GlobalData.nightBool = true
GlobalData.dayBool = false
}
}
}
这是我的代码,用于根据其中一个是真还是假切换背景:
//Day Background
if GlobalData.dayBool == true && GlobalData.nightBool == false {
backgroundColor = GlobalData.dayColor
}
//Night Background
if GlobalData.nightBool == true && GlobalData.dayBool == false {
backgroundColor = GlobalData.nightColor
}
如果您有任何问题,请在下面留下任何问题。我真的需要这方面的帮助。
最佳答案
为您的按钮创建一个 IBAction
并执行下面的 NSUserDefault 部分。
NSUserDefault
我总是喜欢将我的 NSUserDeafult 注册为默认设置,很多人只是继续第二步而不注册。
在 AppDelgate.swift 中注册 NSUserDefault
NSUserDefaults.standardUserDefaults().registerDefaults(["valueName": AnyObject])
设置 Value 到您的 NSUserDefault,这取决于您存储的数据类型,如果您确实注册了,应该与您的注册相匹配。 (下面的 bool 数据类型示例)
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "valueName") //Bool Data Type
确保在将值设置为 NSUserDefault 后同步,这样它会立即更新,否则它会在有机会时更新。
NSUserDefaults.standardUserDefaults().synchronize()
接收值:这将接收 bool 值,因为我们设置了 bool 值并注册了 bool 值。
let Variable: Bool! = NSUserDefaults.standardUserDefaults().boolForKey("valueName")
关于swift - 按下按钮时如何在 NSDefaults 中保存 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34373668/