In fact, the swift language and OC language are essentially the same, and the methods and the like are basically the same. The use of notifications is the same, but the writing format of the code has changed. Below I can do this with a simple small need, and also a notification, with the closure in Swift.
Precautions to use:
1, first ensure that the receiving center exists, in the set Notification Center.
2. Finally, be sure to remove the notification hub.
3, notice also can pass value, put in userinfo inside.
Concrete interface effect, I can not here, I hope you developers, write it again, and then run.
Viewcontroller
//
Viewcontroller.swift
Usage of notifications in Swift
//
Created by Mac on 16/2/5.
COPYRIGHT©2016 year 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);
Remove notification hubs
Nsnotificationcenter.defaultcenter (). Removeobserver (Self, Forkeypath: "text", Context:nil);
}
}
Secondviewcontroller
//
Secondviewcontroller.swift
Usage of notifications in Swift
//
Created by Mac on 16/2/5.
COPYRIGHT©2016 year 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
};
}
}
How to use notifications in Swift