首页 > 解决方案 > 如何使用观察者?为什么我的观察员不在这里工作?

问题描述

我的项目中有两个视图控制器和两个视图控制器类。我想使用通知和观察者从第二个视图控制器更改第一个视图控制器的背景颜色。但它不起作用。我注意到“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)
    }
}

标签: iosswiftswift5

解决方案


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

你可能想通过它零。

从文档中:

一个东西

也就是说,只有这个发送者发送的通知才会传递给观察者。

如果传递nil,通知中心不会使用通知的发送者来决定是否将其传递给观察者。观察者想要接收其通知的对象;

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

另外,我同意 Harish,您应该只使用代表。


推荐阅读