我有2个视图控制器,其中一个带有开关,切换时应显示以下通知。在另一个视图控制器中,我有观察者,应触发以下仅切换布尔值的功能。我无法让观察者工作并进行该函数调用,我在这里做错了吗?我还有另一条通知(未通过用户输入触发),它以相反的方向发送,效果很好。
@IBAction func switchAction(_ sender: Any) {
if switchUI.isOn {
print("Collecting Data ")
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Collect"), object: self)
}
else
{
print("Not Collecting Data")
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Do Not Collect"), object: self)
}
}
func collectDataObserver () {
//Add an Observer
NotificationCenter.default.addObserver(self, selector: #selector(CentralViewController.toggleData(notification:)), name: Notification.Name(rawValue: "Collect"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(CentralViewController.toggleData(notification:)), name: Notification.Name(rawValue: "Do Not Collect"), object: nil)
}
@objc func toggleData(notification: NSNotification) {
let isCollectData = notification.name.rawValue == "Collect"
if(isCollectData){
IsCollectingData = true
}
else
{
IsCollectingData = false
}
}
答案 0 :(得分:1)
您需要致电collectDataObserver()
的{{1}}中的viewDidLoad()
,即
CentralViewController