我的项目中有两个视图控制器类和两个视图控制器类。我想使用通知和观察者从第二个视图控制器更改第一个视图控制器的背景色。但这不起作用。 我注意到“ 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)
}
}
答案 0 :(得分:2)
添加观察者时,会将对象自身传递给它。
您可能希望将其传递为零。
从文档中:
anObject
,即只有此发件人发送的通知会传递到 观察者。
如果您输入nil,则通知中心不会使用通知的 发送者决定是否将其传递给观察者。观察者想要接收其通知的对象;
因此,它唯一会接受来自其的通知的是它本身,这不太可能是您想要的。
此外,我同意Harish,您应该只使用一个委托。
答案 1 :(得分:0)
在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) {}