我想在 userdefault 中保存按钮启用和禁用值。我写了下面的代码,但什么也没发生。请告诉我如何保存和获取按钮启用和禁用值。
我想要,当按下 ibaction 按钮时,它应该禁用,当关闭应用程序并重新打开应用程序时,它应该保存按钮的禁用状态。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var btn2: UIButton!
@IBOutlet weak var btn1: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// let def = UserDefaults.standard.bool(forKey: "val")
// btn1.isEnabled = def
}
override func viewWillAppear(_ animated: Bool) {
let def = UserDefaults.standard.bool(forKey: "val")
print(def)
//btn1.isEnabled = def
}
@IBAction func btn1Pressed(_ sender: UIButton) {
let def = UserDefaults.standard.bool(forKey: "val")
print("Button one pressed")
let otherAlert = UIAlertController(title: "Button 1!!", message: "Here is button one.", preferredStyle: UIAlertControllerStyle.alert)
let okaction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (UIAlertAction) in
print("OK pressed")
self.btn1.isEnabled = false
UserDefaults.standard.set(self.btn1.isEnabled, forKey: "val")
}
let dismiss = UIAlertAction(title: "No", style: UIAlertActionStyle.cancel) { (UIAlertAction) in
self.btn1.isEnabled = true
UserDefaults.standard.set(self.btn1.isEnabled, forKey: "val")
print("No pressed")
}
otherAlert.addAction(dismiss)
otherAlert.addAction(okaction)
present(otherAlert, animated: true, completion: nil)
let def1 = UserDefaults.standard.bool(forKey: "val")
btn1.isEnabled = def1
}
@IBAction func btn2Pressed(_ sender: UIButton) {
print("Button Two pressed")
}
}
最佳答案
不要保存self.btn1.isEnabled
,而是保存您要应用于该值的值。你不能直接这样做吗?
override func viewDidLoad() {
super.viewDidLoad()
// You need to check if key is present or else you will get false as default value and your button will disabled only
if isKeyPresentInUserDefaults(key: "val") {
let def = UserDefaults.standard.bool(forKey: "val")
btn1.isEnabled = def
}
}
// Check key is present or not
func isKeyPresentInUserDefaults(key: String) -> Bool {
return UserDefaults.standard.object(forKey: key) != nil
}
@IBAction func btn1Pressed(_ sender: UIButton) {
let defaults = UserDefaults.standard
defaults.set(false, forKey: "val")
print("Button one pressed")
let otherAlert = UIAlertController(title: "Button 1!!", message: "Here is button one.", preferredStyle: UIAlertControllerStyle.alert)
let okaction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (UIAlertAction) in
print("OK pressed")
self.btn1.isEnabled = false
defaults.set(false, forKey: "val")
}
let dismiss = UIAlertAction(title: "No", style: UIAlertActionStyle.cancel) { (UIAlertAction) in
self.btn1.isEnabled = true
defaults.set(true, forKey: "val")
print("No pressed")
}
otherAlert.addAction(dismiss)
otherAlert.addAction(okaction)
present(otherAlert, animated: true, completion: nil)
// No need of these 2 lines
let def1 = defaults.bool(forKey: "val")
btn1.isEnabled = def1
}
关于ios - 如何使用用户默认值保存和获取按钮启用和禁用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50721356/