快速-将UserDefaults添加到NotificationCenter

问题描述 投票:0回答:2

我实现了NotificationCenter,只要您在特定的TableViewCell上点击以在另一个ViewController中执行该通知,对于本示例,其他ViewController背景颜色变为粉红色,效果很好,但是我的问题是如何使用UserDefaults保存与ViewController相同的粉红色状态?

为了更好地说明这一点:

  • ViewController#2

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

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

    我想实现什么?

使用UserDefaults

ViewController#1中保存粉红色的状态

ViewController#1代码

-viewDidLoad

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

-TestNotification函数

@objc func testNotifcation(notification: NSNotification) { 

    table.backgroundColor = UIColor.systemPink

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

ViewController#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
        {
            ...
        }
    }
}

[只要您在一个特定的TableViewCell上点击以在另一个ViewController内执行该通知的情况下,便实现了一个NotificationCenter,在本示例中为另一个ViewController背景色...

ios swift uitableview nsuserdefaults uicolor
2个回答
0
投票

您在调用通知方法时可以在UserDefaults中设置颜色。因此,请在ViewController1


0
投票

如果要在UIColor中保存UserDefaults,则无法直接实现,因为UserDefaults无法保存UIColor类型的值,但是我已经完成了相同的事情,但是使用的方式不同

] >
  • 首先,您必须创建要保存的Array的Rob值的UIColor,然后可以将该数组保存在UserDefaults中并在任何地方使用它
© www.soinside.com 2019 - 2024. All rights reserved.