从另一个 class (Swiftui 4) 调用 userDefaults

call userDefults from another class (Swift4)

我希望我的代码能够在 viewController 中调用用户 Default 并在可能的情况下在 twoViewController 中显示其操作。因此,当且仅当操作在 class viewController 中实施时,我希望两个 class 背景都是红色的。

 import UIKit

 class ViewController: UIViewController {
let defaults = UserDefaults.standard

@IBAction func press () {
  view.backgroundColor = .red
  UserDefaults.standard.set(view.backgroundColor, forKey: “userlogin”)
}
  }
class twoViewController: UIViewController {

//load Userdefults from class ViewController in view did load
}

我想你可以注册一个更新 twoViewController 背景颜色的通知。

@IBAction func press () {
  view.backgroundColor = .red
  UserDefaults.standard.set(view.backgroundColor, forKey: “userlogin”)
  UserDefaults.standard.synchronize()
  Notification.Name("NotificationIdentifier"), object: nil)
}

注册更新通知UI

NotificationCenter.default.addObserver(self, selector: 
  #selector(self.methodOfReceivedNotification(notification:)), name: 
    Notification.Name("NotificationIdentifier"), object: nil)

并在函数中添加刷新代码

@objc func methodOfReceivedNotification(notification: Notification){
   // refresh UI code
   // load the color value
   // set up new value to background color
 }

在viewController中设置:

let data = NSKeyedArchiver.archivedData(withRootObject: UIColor.red as Any)
UserDefaults.standard.set(data, forKey: "userlogin")  

在两个ViewController中:

if let data = UserDefaults.standard.value(forKey: "userlogin") as? Data, let color = NSKeyedUnarchiver.unarchiveObject(with: data) as? UIColor{
        self.view.backgroundColor = color
    }