9.4、通知中心

2018-06-27  本文已影响6人  艾希_可可

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!)")
    }
上一篇 下一篇

猜你喜欢

热点阅读