场景:A页面跳转到B页面,B页面返回到A页面,(B页面给A页面传值)
B页面逻辑:发送通知
A页面逻辑:创建通知,移除通知
B页面代码:
@IBAction func back(_sender:UIButton) {
let dic = ["name":passTf.text??""]
//多值传递
NotificationCenter.default.post(name:NSNotification.Name(rawValue:"value"), object:nil, userInfo: dic)
//单值传递
NotificationCenter.default.post(name:NSNotification.Name(rawValue:"passValue"), object:"zyy",userInfo:nil)
self.navigationController?.popViewController(animated:true)
}
A页面代码:
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.title="第一页"
NotificationCenter.default.addObserver(self, selector:#selector(change(info:)), name:NSNotification.Name(rawValue:"value"), object:nil)
NotificationCenter.default.addObserver(self, selector:#selector(change1(info:)), name:NSNotification.Name(rawValue:"passValue"), object:nil)
}
@objc func change(info:NSNotification) {
print(info.userInfo) // 类型为[AnyHashable,Any]
let dic = info.userInfo as! Dictionary
textLabel.text = dic[AnyHashable("name")] as! String
}
@objc func change1(info:NSNotification) {
print(info.object)
}