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的事情。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值