zoukankan      html  css  js  c++  java
  • swift_通知的使用

    import UIKit

    class ViewController: UIViewController {
    //定义通知的名字,Notification 的“名字”不再是字符串类型,而是 Notification.Name 类型
    let myNotification = Notification.Name(rawValue:"MyNotification")
    override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let nc = NotificationCenter.default
    //发送通知
    nc.post(name:myNotification,
    object: nil,
    userInfo:["message":"Hello there!", "date":Date()])
    }
    override func viewDidLoad() {
    super.viewDidLoad()
    let nc = NotificationCenter.default
    //添加通知,通知处理尽量
    nc.addObserver(forName:myNotification, object:nil, queue:nil, using:catchNotification)

    }
    func catchNotification(notification:Notification) -> Void {
    print("Catch notification")
    //guard语句和if语句有点类似,都是根据其关键字之后的表达式的布尔值决定下一步执行什么。但与if语句不同的是,guard语句只会有一个代码块,不像if语句可以if else多个代码块。
    //userInfo变量的作用域是在整个方法体内
    //guard方法可以自动解包
    guard let userInfo = notification.userInfo,
    let message = userInfo["message"] ,
    let date = userInfo["date"] else {
    print("No userInfo found in notification")
    return
    }

    //提醒框
    let alert = UIAlertController(title: "Notification!",
    message:"(message) received at (date)",
    preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
    self.present(alert, animated: true, completion: nil)
    }
    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }


    }

  • 相关阅读:
    v​s​快​捷​键
    sequelize 基本操作
    服务器重启,自动重启httpd
    svn使用方法以及使用教程
    非常全的VsCode快捷键
    原生JS forEach()和map()遍历的区别以及兼容写法
    JS中 map, filter, some, every, forEach, for in, for of 用法总结
    map的使用
    Window和Mac下端口占用情况及处理方式
    vue实现分环境打包步骤(给不同的环境配置相对应的打包命令)
  • 原文地址:https://www.cnblogs.com/lcl15/p/7573484.html
Copyright © 2011-2022 走看看