Swift3.0 通知

通知 –> 本文不做多个页面接收通知,只在两个页面之间发送和接收,多个页面类似

SecondViewController代码块

import UIKit


class SecondViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        let btn = UIButton()
        btn.setTitle("返回", for: .normal)
        btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        btn.backgroundColor = UIColor.purple
        btn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
        self.view.addSubview(btn)
    }

    func backBtnClick() {
        // 发送通知 post
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "CallBackNotification"), object: self, userInfo: ["info": "second controller "])

        self.navigationController?.popViewController(animated: true)

    }

}

FirstViewController

import UIKit

class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white
        let btn = UIButton()
        btn.setTitle("跳转", for: .normal)
        btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        btn.backgroundColor = UIColor.purple
        btn.addTarget(self, action: #selector(pushBtnClick), for: .touchUpInside)
        self.view.addSubview(btn)


        // 接收通知
        NotificationCenter.default.addObserver(self, selector: #selector(callbackNotification(notification:)), name: NSNotification.Name(rawValue: "CallBackNotification"), object: nil)
    }

    func pushBtnClick() {

        let secondVC = SecondViewController()
        self.navigationController?.pushViewController(secondVC, animated: true)

    }

    // 收到通知要执行方法
    func callbackNotification(notification: Notification) {

        let userInfo = notification.userInfo as! [String: AnyObject]
        print(userInfo["info"] as AnyObject,".....")

    }

    // 移除通知监听
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}

好了,简单的通知就这么实现了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值