Swift - 将 UserDefaults 添加到 NotificationCenter

布罗斯基

每当您点击特定的TableViewCell以在另一个ViewController 中执行该通知时,我都实现了一个NotificationCenter,对于这个示例,另一个ViewController背景颜色变为粉红色,这可以正常工作,但我的问题是如何保存粉红色的状态相同在那个ViewController 中使用UserDefaults

为了更好地澄清这一点:

  • ViewController #2包含按下时执行操作的 TableViewCell

  • ViewController #1是颜色变为粉红色的视图。

我想达到什么目标?

使用UserDefaultsViewController #1 中保存粉红色的状态

视图控制器 #1 代码

- viewDidLoad

override func viewDidLoad()
{
    NotificationCenter.default.addObserver(self, selector: #selector(BrandTableViewController.testNotifcation(notification:)), name:NSNotification.Name(rawValue: "refresh"), object: nil);
}

- 测试通知功能

@objc func testNotifcation(notification: NSNotification) { 

    table.backgroundColor = UIColor.systemPink

    print("This is a message to say it is working")
}

视图控制器 #2 代码

didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if indexPath.row == 0
    {

        if traitCollection.userInterfaceStyle == .light
        {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil, userInfo: nil)
            self.dismiss(animated: true, completion: nil)
        }
        else if traitCollection.userInterfaceStyle == .dark
        {
            ...
        }
    }
}
萨加·乔汉

您可以在UserDefaults调用通知方法时设置颜色因此,在ViewController1 中更新您的代码如下

@objc func testNotifcation(notification: NSNotification) { 

    table.backgroundColor = UIColor.systemPink

    let colorData = NSKeyedArchiver.archivedData(withRootObject: UIColor.systemPink)
    UserDefaults.standard.set(colorData, forKey: "savedColor")
    UserDefaults.standard.synchronize()

    print("This is a message to say it is working")
}

然后,在视图中加载,您需要添加代码来获取保存的颜色并将其设置为背景。因此,在更新的代码viewDidLoadViewController1

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(BrandTableViewController.testNotifcation(notification:)), name:NSNotification.Name(rawValue: "refresh"), object: nil);

    if let colorData = UserDefaults.standard.value(forKey: "savedColor") as? Data,
        let savedColor = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
    {
        table.backgroundColor = savedColor
    }
}

我希望这能帮到您。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章