使用 userDefaults 保存 UIView

saving UIViews with userDefaults

我有一个项目,我在其中放置了一个视图,一个用于隐藏视图的按钮,一个用于显示视图,然后是一个标签和一个按钮(每次按下按钮时,您都会得到一个不同于 0 的数字)

@IBAction weak var myView: UIView!
@IBAction Weak var myLabel: UILabel!
 var numbers: [Int] = [1, 7, 9, 6, 0, 3, 10, 45, 2, 83].shuffled()

override func viewDidLoad() {
        super.viewDidLoad()
        myView.isHidden = true
      myLabel.text = "\(UserDefaults.standard.integer(forKey: "Key"))"


    }

 @IBAction func closeView(_ sender: Any) {
myView.isHidden = true
myLabel.text = 0
UserDefaults.standard.removeObject(forKey: "Key")
}

 @IBAction func showView(_ sender: Any) {
myView.isHidden = false
}

 @IBAction func addNumber(_ sender: Any) {
 let oneNum = numbers.shuffled().first

 UserDefaults.standard.set(oneNum, forKey: "Key")
            myLabel.text = "\(UserDefaults.standard.integer(forKey: "Key"))"
}

我想要的是添加一个功能,如果标签显示的数字不是 0,我可以自动显示 myView。我该怎么做?

我想你想要的是这样的:

@IBOutlet weak var myView: UIView!
@IBOutlet weak var myLabel: UILabel!
var numbers: [Int] = [1, 7, 9, 6, 0, 3, 10, 45, 2, 83].shuffled()

var currentNumber: Int {
    didSet {
        UserDefaults.standard.set(currentNumber, forKey: "currentNumberKey")
        myLabel.text = "\(currentNumber)"

        // Hide if number is 0, else show
        myView.isHidden = currentNumber == 0
    }
}

private func setNextNumber() {
    currentNumber = numbers.shuffled().first!
}

override func viewDidLoad() {
    super.viewDidLoad()
    currentNumber = UserDefaults.standard.integer(forKey: "currentNumberKey")
}

@IBAction func closeView(_ sender: Any) {
    currentNumber = 0
}

@IBAction func showView(_ sender: Any) {
    myView.isHidden = false
}

@IBAction func addNumber(_ sender: Any) {
    setNextNumber()
}

设置变量currentNumber将自动更新标签文本,并自动隐藏myView(如果currentNumber为零)或显示myView(如果 currentNumber 不为零)。

viewDidLoad恢复状态。如果 UIViewController 消失和出现,状态会自动保持,所以在 viewWillAppear/viewDidAppear 中不需要任何东西viewWillDisappear/viewDidDisappear