我实现了NotificationCenter,只要您在特定的TableViewCell上点击以在另一个ViewController中执行该通知,对于本示例,其他ViewController背景颜色变为粉红色,效果很好,但是我的问题是如何使用UserDefaults保存与ViewController相同的粉红色状态?
为了更好地说明这一点:
ViewController#2
包含在按下时执行操作的TableViewCellViewController#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背景色...
您在调用通知方法时可以在UserDefaults
中设置颜色。因此,请在ViewController1
如果要在UIColor
中保存UserDefaults
,则无法直接实现,因为UserDefaults
无法保存UIColor
类型的值,但是我已经完成了相同的事情,但是使用的方式不同
Array
的Rob值的UIColor
,然后可以将该数组保存在UserDefaults
中并在任何地方使用它