通知 –> 本文不做多个页面接收通知,只在两个页面之间发送和接收,多个页面类似
SecondViewController代码块
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let btn = UIButton()
btn.setTitle("返回", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
btn.backgroundColor = UIColor.purple
btn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
self.view.addSubview(btn)
}
func backBtnClick() {
// 发送通知 post
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "CallBackNotification"), object: self, userInfo: ["info": "second controller "])
self.navigationController?.popViewController(animated: true)
}
}
FirstViewController
import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let btn = UIButton()
btn.setTitle("跳转", for: .normal)
btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
btn.backgroundColor = UIColor.purple
btn.addTarget(self, action: #selector(pushBtnClick), for: .touchUpInside)
self.view.addSubview(btn)
// 接收通知
NotificationCenter.default.addObserver(self, selector: #selector(callbackNotification(notification:)), name: NSNotification.Name(rawValue: "CallBackNotification"), object: nil)
}
func pushBtnClick() {
let secondVC = SecondViewController()
self.navigationController?.pushViewController(secondVC, animated: true)
}
// 收到通知要执行方法
func callbackNotification(notification: Notification) {
let userInfo = notification.userInfo as! [String: AnyObject]
print(userInfo["info"] as AnyObject,".....")
}
// 移除通知监听
deinit {
NotificationCenter.default.removeObserver(self)
}
}