如何使用observer?为什么我的观察员不在这里工作



在我的项目中有两个视图控制器和两个视图控件类。我想使用通知和观察者从第二视图控制器更改第一视图控制器的背景颜色。但它不起作用。我注意到"changeViewControllerColor(_:("方法没有调用。

第一视图控制器:

import UIKit
let colorChangeNotificationKey = "changeFirstVcColor"
class FirstViewController: UIViewController {
let notiName = Notification.Name(rawValue: colorChangeNotificationKey)
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
observer()
}

func observer() {
NotificationCenter.default.addObserver(self, selector: #selector(FirstViewController.changeViewControllerColor(_:)), name: self.notiName, object: self)
}
@objc func changeViewControllerColor(_: NSNotification) {
self.view.backgroundColor = UIColor.white
}

@IBAction func button(_ sender: UIButton) {
let vc = storyboard?.instantiateViewController(identifier: "secondViewController") as! SecondViewController
navigationController?.pushViewController(vc, animated: true)
}
}

第二视图控制器:

import UIKit
class SecondViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
label.text = "First VC colour is white now"
let notiName = Notification.Name(rawValue: colorChangeNotificationKey)
NotificationCenter.default.post(name: notiName, object: nil)
}
}

当您添加观察者时,您将向其传递对象self。

你可能想零封对手。

来自文件:

anObject

也就是说,只有此发件人发送的通知才会传递到观察者

如果你通过了nil,通知中心就不会使用通知发件人决定是否将其发送给观察员。观察者想要接收其通知的对象;

所以它唯一会接受通知的是它自己,这很可能不是你想要的。

此外,我同意哈里什的观点,你应该使用一名代表。

在SecondViewController中:

NotificationCenter.default.post(name: Notification.Name("changeFirstVcColor"), object: nil)

在FirstViewController中:

NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("changeFirstVcColor"), object: nil)
@objc func methodOfReceivedNotification(notification: Notification) {}

相关内容

最新更新