OC中Blocks反向传值和Swift中Closure反向传值的差别,下面直接贴上代码:
一、第一个界面
[objc] view plain copy importUIKit classZWRootVIEwController:UIVIEwController{ init(nibnamenibnameOrNil:String?,bundlenibBundleOrNil:NSBundle?){ super.init(nibname:nibnameOrNil,bundle:nibBundleOrNil) //Custominitialization } 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{ //functionbodygoeshere 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. } */ }二、第二个界面
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)") } 总结
以上是内存溢出为你收集整理的Swift利用闭包(closure)来实现传值-->前后两个控制器的反向传值全部内容,希望文章能够帮你解决Swift利用闭包(closure)来实现传值-->前后两个控制器的反向传值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)