Swift利用闭包(closure)来实现传值-->前后两个控制器的反向传值

前端之家收集整理的这篇文章主要介绍了Swift利用闭包(closure)来实现传值-->前后两个控制器的反向传值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

OC中Blocks反向传值和Swift中Closure反向传值的差别,下面直接贴上代码:@H_301_1@

一、第一个界面@H_301_1@

@H_301_1@

[objc] view plain copy
  1. importUIKit
  2. classZWRootViewController:UIViewController{
  3. init(nibNamenibNameOrNil:String?,bundlenibBundleOrNil:NSBundle?){
  4. super.init(nibName:nibNameOrNil,bundle:nibBundleOrNil)
  5. //Custominitialization
  6. }
  7. varmyLabel:UILabel?
  8. overridefuncviewDidLoad(){
  9. super.viewDidLoad()
  10. varitem=UIBarButtonItem(title:"下一页",style:UIBarButtonItemStyle.Plain,target:self,action:"nextBtnClicked")
  11. self.navigationItem.rightBarButtonItem=item
  12. myLabel=UILabel(frame:CGRectMake(0,100,320,50))
  13. myLabel!.text="Closure"
  14. myLabel!.textAlignment=NSTextAlignment.Center
  15. self.view.addSubview(myLabel!)
  16. //Doanyadditionalsetupafterloadingtheview.
  17. funcsomeFunctionThatTakesAClosure(string:String)->Void{
  18. //functionbodygoeshere
  19. myLabel!.text=string
  20. funcnextBtnClicked(){
  21. letsecond=ZWSecondViewController(nibName:nil,bundle:nil)
  22. //将当前someFunctionThatTakesAClosure函数指针传到第二个界面,第二个界面的闭包拿到该函数指针后会进行回调该函数
  23. second.initWithClosure(someFunctionThatTakesAClosure)
  24. self.navigationController.pushViewController(second,animated:true)
  25. }
  26. overridefuncviewWillDisappear(animated:Bool){
  27. myLabel!.hidden=true
  28. overridefuncviewWillAppear(animated:Bool){
  29. myLabel!.hidden=false
  30. overridefuncdidReceiveMemoryWarning(){
  31. super.didReceiveMemoryWarning()
  32. //DispoSEOfanyresourcesthatcanberecreated.
  33. /*
  34. //#pragmamark-Navigation
  35. //Inastoryboard-basedapplication,youwilloftenwanttodoalittlepreparationbeforenavigation
  36. overridefuncprepareForSegue(segue:UIStoryboardSegue?,sender:AnyObject?){
  37. //Getthenewviewcontrollerusing[seguedestinationViewController].
  38. //Passtheselectedobjecttothenewviewcontroller.
  39. }
  40. */
  41. }

二、第二个界面

@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)")
  • }
  • 原文链接:https://www.f2er.com/swift/323383.html

    猜你在找的Swift相关文章