微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift - NotificationCenter通知的基本使用

不管是通知,还是代理,闭包,说白了,其主要目的都是在不同的类之间传值,比如你想在classA中得到classB中的东西,classC中得到classD中的东西。

下面是一个浅显的例子:

// 点击按钮present到控制器ItemViewController中
 @IBAction func next(_ sender: Any) {
        let nextVC = ItemViewController(nibName: "ItemViewController", bundle: nil)
        self.present(nextVC, animated: true, completion: nil) 
            
        //下面的代码相当于注册一个通知,用来监听上面 self.present...执行完之后的时间点      
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Todo"), object: nil)
  }
//ItemViewController中
  override func viewDidLoad() {
        super.viewDidLoad()
        
    NotificationCenter.default.addobserver(self, selector: #selector(todoSomething), name:NSNotification.Name(rawValue: "Todo"), object: nil)
        
  }

 @objc func todoSomething(){
    self.view.backgroundColor = .blue
 }

NotificationCenter.default.post(name: NSNotification.Name(rawValue: “Todo”), object: nil)这段代码告诉我跳转到ItemViewController之后我要记录一个东西。

NotificationCenter.default.addobserver(self, selector: #selector(todoSomething), name:NSNotification.Name(rawValue: “Todo”), object: nil)这段代码接收上面记录的东西,也就是记录了跳转之后的时间点。

func todoSomething()调用这个方法就是说明我要在跳转到ItemViewController之后做一些todoSomething的事情。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐