9.4、通知中心

import UIKit

class OneViewController: UIViewController {
// 定义通知的名称
let refreshTableView = "refreshTableView"
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.title = "首页"
self.navigationController?.navigationBar.barTintColor = UIColor.red
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.blue]
// 接收完成要移除观察者(deinit:相当于OC中的dealloc)
// NotificationCenter.default.removeObserver(self, name: (NSNotification.Name(rawValue: refreshTableView)), object: nil)
// 为通知添加观察者(接收者)
NotificationCenter.default.addObserver(self, selector: #selector(test2(_:)), name: NSNotification.Name(rawValue: refreshTableView), object: nil)

    let btn = UIButton(frame: CGRect(x: 100, y: 200, width: 100, height: 40))
    self.view.addSubview(btn)
    btn.backgroundColor = UIColor.gray
    btn.setTitle("Touch Me", for: .normal)
    btn.addTarget(self, action: #selector(btnAction), for: .touchUpInside)
}
@objc func btnAction(){
    print("点击按钮发送通知")
    let name = "Tina"
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: refreshTableView), object: name)
}
func test2(_ info:Notification) {
    print("一页面收到通知\(info.object!)")
}

}

import UIKit

class FourViewController: UIViewController {
    let refreshTableView = "refreshTableView"
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.red
        self.navigationController?.navigationBar.topItem?.title = "我的"
        
        NotificationCenter.default.addObserver(self, selector: #selector(test2(_:)), name: NSNotification.Name(rawValue: refreshTableView), object: nil)

    }
    func test2(_ info:Notification) {
        print("四页面收到通知\(info.object!)")
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容