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