美文网首页
iOS 通知中心 发布-订阅者模式 NotificationC

iOS 通知中心 发布-订阅者模式 NotificationC

作者: 已经多年不写Unity | 来源:发表于2018-12-26 16:11 被阅读0次

    写了几天iOS已经轻车熟路了~~~~~~

    
    //
    //  ViewController.swift
    //  Xcodetest
    //
    //  Created by Wirhui on 2018/12/26.
    //  Copyright © 2018 Wirhui. All rights reserved.
    //
    
    import UIKit
    import  NotificationCenter
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
        
        
        //单击按钮发送调用的数据
        @IBAction func NotifyTest(_ sender: Any) {
            /// 发送简单数据
    //        NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "Hello"), object: "Hello 2017")
            
            /// 发送额外数据
            let info = ["name":"Eric","age":21] as [String : Any]
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "Hello"), object: "GoodBye 2016", userInfo: info)
    
            
        }
        
        //设置监听Hello
        override func viewDidAppear(_ animated: Bool) {
             print("页面出现")
            NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name: NSNotification.Name.init("Hello"), object: nil)
            
        }
        
        override func viewDidDisappear(_ animated: Bool) {
            print("页面消失")
        }
        
        @objc func notificationAction(info:NSNotification)  {
            print("监听到消息\(info)")
        }
        
        //移除监听
        deinit {
            /// 移除通知
            NotificationCenter.default.removeObserver(self)
        }
    
    
    }
    
    
    
    
    

    相关文章

      网友评论

          本文标题:iOS 通知中心 发布-订阅者模式 NotificationC

          本文链接:https://www.haomeiwen.com/subject/xjnhlqtx.html