OC中Blocks反向传值和Swift中Closure反向传值的差别,下面直接贴上代码:@H_301_1@
一、第一个界面@H_301_1@
@H_301_1@
- importUIKit
-
- classZWRootViewController:UIViewController{
- init(nibNamenibNameOrNil:String?,bundlenibBundleOrNil:NSBundle?){
- super.init(nibName:nibNameOrNil,bundle:nibBundleOrNil)
-
- }
- varmyLabel:UILabel?
- overridefuncviewDidLoad(){
- super.viewDidLoad()
- varitem=UIBarButtonItem(title:"下一页",style:UIBarButtonItemStyle.Plain,target:self,action:"nextBtnClicked")
- self.navigationItem.rightBarButtonItem=item
-
- myLabel=UILabel(frame:CGRectMake(0,100,320,50))
- myLabel!.text="Closure"
- myLabel!.textAlignment=NSTextAlignment.Center
- self.view.addSubview(myLabel!)
- //Doanyadditionalsetupafterloadingtheview.
- funcsomeFunctionThatTakesAClosure(string:String)->Void{
-
- myLabel!.text=string
- funcnextBtnClicked(){
- letsecond=ZWSecondViewController(nibName:nil,bundle:nil)
- //将当前someFunctionThatTakesAClosure函数指针传到第二个界面,第二个界面的闭包拿到该函数指针后会进行回调该函数
- second.initWithClosure(someFunctionThatTakesAClosure)
- self.navigationController.pushViewController(second,animated:true)
- }
- overridefuncviewWillDisappear(animated:Bool){
- myLabel!.hidden=true
- overridefuncviewWillAppear(animated:Bool){
- myLabel!.hidden=false
- overridefuncdidReceiveMemoryWarning(){
- super.didReceiveMemoryWarning()
- //DispoSEOfanyresourcesthatcanberecreated.
- /*
- //#pragmamark-Navigation
- //Inastoryboard-basedapplication,youwilloftenwanttodoalittlepreparationbeforenavigation
- overridefuncprepareForSegue(segue:UIStoryboardSegue?,sender:AnyObject?){
- //Getthenewviewcontrollerusing[seguedestinationViewController].
- //Passtheselectedobjecttothenewviewcontroller.
- }
- */
- }
二、第二个界面
@H_301_1@
copy
//类似于OC中的typedef
typealiassendValueClosure=(string:String)->Void
ZWSecondViewController:UIViewController{
i:Int?
//声明一个闭包
myClosure:sendValueClosure?
//下面这个方法需要传入上个界面的someFunctionThatTakesAClosure函数指针
funcinitWithClosure(closure:sendValueClosure?){
//将函数指针赋值给myClosure闭包,该闭包中涵盖了someFunctionThatTakesAClosure函数中的局部变量等的引用
myClosure=closure
init(nibNamenibBundleOrNil:NSBundle?){
bundle:nibBundleOrNil)
i=0
varbtn=UIButton.buttonWithType(UIButtonType.System)as?UIButton
btn!.frame=CGRectMake(0,50)
btn!.setTitle("点击我",forState:UIControlState.Normal)
btn!.addTarget("action",0); background-color:inherit">forControlEvents:UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
funcaction(){
i=i!+1
//判空
ifmyClosure{
//闭包隐式调用someFunctionThatTakesAClosure函数:回调。
myClosure!(string:"好好哦\(i)")
}