ios - 如何使用观察者?为什么我的观察员不在这里工作?
问题描述
我的项目中有两个视图控制器和两个视图控制器类。我想使用通知和观察者从第二个视图控制器更改第一个视图控制器的背景颜色。但它不起作用。我注意到“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 传递给它。
你可能想通过它零。
从文档中:
一个东西
也就是说,只有这个发送者发送的通知才会传递给观察者。
如果传递nil,通知中心不会使用通知的发送者来决定是否将其传递给观察者。观察者想要接收其通知的对象;
所以它唯一会接受通知的就是它自己,这可能不是你想要的。
另外,我同意 Harish,您应该只使用代表。
推荐阅读
- python - 如何在python中的字典元素列表中访问字典?
- c# - 机器人框架 V4 网络聊天中的每个用户的 AD 身份验证令牌并不相同
- svm - “带”边缘上的数据点,围绕使带外所有数据点冗余的分隔符,称为什么?
- c++ - Boost 能做什么现代 C++ 做不到的?
- python - 无法获取输出图像
- python - 在 Python 中,如何从一个字符串中返回多个匹配的子字符串
- time-series - facebook 先知:如何将结果分解为季节性和趋势成分
- python - 如何将 Pandas 系列转换为 Numpy 数组并保持秩序?
- java - 如何在 JUnit 测试期间在 @Configuration 类中自动装配?
- react-native - 在 Android 9 上模拟时,Build.grad 不加载“index.js”包