swift中通知的使用方法

其实swift语言和OC语言,在本质上都是一样,其里面的方法之类的也基本相同。通知的使用方法也是一样,只是代码的书写格式发生了改变而已。下面我通过一个简单的小需求,也讲一讲通知,用swift中的闭包,也能完成此功能。

使用通知需要注意事项:

 1,先确保接收中心存在,在设置通知中心。

 2,最后一定要移除通知中心。

 3,通知也是可以传值的,放在userInfo里面。

 

界面效果图:

 

ViewController

//

//  ViewController.swift

//  swift中通知的用法

//

//  Created by mac on 16/2/5.

//  Copyright © 2016年 ZY. All rights reserved.

//

 

import UIKit

 

class ViewController: UIViewController {

 

    @IBOutlet weak var textF: UITextField!

    

    

    @IBOutlet weak var presentButton: UIButton!

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        presentButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside);

        

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationAction:", name: "name", object: nil);

        

    }

 

   

    func notificationAction(fication : NSNotification){

 

//        print("\(fication.userInfo!["text"])");

 

        let text = fication.userInfo!["text"]  as! String;

        self.textF.text = text;

        

    }

    

    

    func buttonAction(btn:UIButton){

        

        

        let viewC = SecondViewController(nibName:"SecondViewController",bundle: nil);

        

        self.presentViewController(viewC, animated: true) { () -> Void in

            

        };

        

    }

    

    override func viewDidDisappear(animated: Bool) {

        super.viewDidDisappear(animated);

        //移除通知中心

       // NSNotificationCenter.defaultCenter().removeObserver(self, forKeyPath: "text", context: nil);

    }

 

}

 

 

SecondViewController

//

//  SecondViewController.swift

//  swift中通知的用法

//

//  Created by mac on 16/2/5.

//  Copyright © 2016年 ZY. All rights reserved.

//

 

import UIKit

 

class SecondViewController: UIViewController {

 

    @IBOutlet weak var textF: UITextField!

    

    

    @IBOutlet weak var disButton: UIButton!

    

    override func viewDidLoad() {

        super.viewDidLoad()

 

        disButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside);

    

    }

    

 

    func buttonAction(btn:UIButton){

        

        NSNotificationCenter.defaultCenter().postNotificationName("name", object: nil , userInfo: ["text":textF.text!]);

            

        self.dismissViewControllerAnimated(true) { () -> Void in

        

        };

        

        

    }

    

    

}

 

转载于:https://www.cnblogs.com/zxh-iOS/p/5185278.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值