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