[英]Save checkbox button state using userdefaults in swift
view controller had two check boxes buttons 1.chekcIn 2.checkOut 视图控制器具有两个复选框按钮1.chekcIn 2.checkOut
am saving the checkIN [ checkbox button] status in user defaults, working fine but when am using that userdefaults key in Nextviewcontroller its always showing true and not running into false block this is the code 我正在将checkIN [复选框按钮]状态保存为用户默认值,工作正常,但是当在Nextviewcontroller中使用该userdefaults键时,它始终显示为true,而没有遇到false块,这是代码
inHomeview controller inHomeview控制器
@IBAction func CheckInButtonClick(_ sender: UIButton) {
for senderdata in checkINOUT {
senderdata.setImage( UIImage(named:"uncheck1"), for: .normal)
print("uncheck is called")
}
sender.setImage(UIImage(named:"check1"), for: .normal)
prefs.set(true, forKey: "check")
prefs.synchronize()
}
nextviewcontroller nextviewcontroller
override func viewDidLoad() {
super.viewDidLoad()
{
let prefs:UserDefaults = UserDefaults.standard
if prefs.bool(forKey: "check") ==true
{
print("select")
} else {
print("unselect")
}
}
check box select its execute main block if unselect execute else block 复选框,如果取消选择执行其他块,则选择其执行主块
how to over come this problem where I did mistake 如何克服我犯错的问题
You´re not setting your userDefault
value to false
. 您没有将userDefault
值设置为false
。 You´re only setting it to true, that´s why it´s always true
. 您只需将其设置为true,这就是为什么它始终为true
。 And btw no need to use synchronize()
Change your code to the following instead: 而且顺便说一句,无需使用synchronize()
将代码更改为以下内容:
HomeViewController: HomeViewController:
@IBAction func CheckInButtonClick(_ sender: UIButton) {
for senderdata in checkINOUT {
senderdata.setImage( UIImage(named:"uncheck1"), for: .normal)
print("uncheck is called")
}
sender.setImage(UIImage(named:"check1"), for: .normal)
UserDefaults.standard.set(true, forKey: "check")
}
NextViewController: NextViewController:
override func viewDidLoad() {
super.viewDidLoad()
if UserDefaults.standard.bool(forKey: "check") {
print("select")
} else {
print("unselect") {
}
}
So do check where you want to set your check
value to false
and use it. 因此,请检查要在哪里将check
值设置为false
并使用它。
Update: 更新:
Just do this check: 只需执行以下检查:
if UserDefaults.standard.set(true, forKey: "check") {
// Show data
} else {
// segue to another viewController
}
When you set "check" value as true once, it will always true, until you set "check" value to false. 一次将“ check”值设置为true时,它将始终为true,直到将“ check”值设置为false。 I think you should add some code to set "check" to false, when user not select the checkbox. 我认为您应该添加一些代码,以在用户未选中复选框时将“ check”设置为false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.