欢迎来到代码驿站!

当前位置:首页 >

Swift中通知中心(NotificationCenter)的使用示例

时间:2021-04-11 08:55:30|栏目:|点击:

前言

本文主要介绍了关于Swift通知中心(NotificationCenter)使用的相关内容,NotificationCenter是Swift中一个调度消息通知的类,采用单例模式设计,实现传值、回调等作用。

通知的作用还是挺强大的,对于两个不相关的控制器之间,要进行信息的传递,使用通知是个不错的选择,下面话不多说了,来一起看看详细的使用方法吧。

1、添加通知

  /// 通知名
  let notificationName = "XMNotification"
  /// 自定义通知
  NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name: NSNotification.Name(rawValue: notificationName), object: nil)

2、设置监听方法

 /// 接受到通知后的方法回调
 @objc private func notificationAction(noti: Notification) {
  /// 获取键盘的位置/高度/时间间隔...
  print(noti)
 }

3、在通知用完后及时销毁

 /// 析构函数.类似于OC的 dealloc
 deinit {
  /// 移除通知
  NotificationCenter.default.removeObserver(self)
 }

4、发送通知

 /// 发送简单数据
 NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "XMNotification"), object: "Hello 2017")

 /// 发送额外数据
 let info = ["name":"Eric","age":21] as [String : Any]
 NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "XMNotification"), object: "GoodBye 2016", userInfo: info)

通知在系统中的运用,监听键盘的变动

  /// 通知中心监听键盘的变化
  #selector(notificationAction), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)

有关键盘的其他通知名称

  public static let UIKeyboardWillShow: NSNotification.Name
  /// 键盘显示完毕
  public static let UIKeyboardDidShow: NSNotification.Name
  /// 键盘将要隐藏
  public static let UIKeyboardWillHide: NSNotification.Name
  /// 键盘隐藏完毕
  public static let UIKeyboardDidHide: NSNotification.Name
  /// 键盘将要改变自身的frame
  public static let UIKeyboardWillChangeFrame: NSNotification.Name
  /// 键盘frame改变完成
  public static let UIKeyboardDidChangeFrame: NSNotification.Name

总结

上一篇:vmware虚拟机安装安卓Android x86的方法步骤

栏    目:

下一篇:Powershell小技巧之通过EventLog查看近期电脑开机和关机时间

本文标题:Swift中通知中心(NotificationCenter)的使用示例

本文地址:http://www.codeinn.net/misctech/98958.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有