
基本 *** 作就是在第二个页面定义一个闭包函数,然后在第一个页面将定义好的函数,通过函数指针传递到第二个页面,然后就阔以了。废话不多说,直接上代码
//// VIEwController.swift// SwiftClosure//// Created by 程磊 on 16/4/15.// copyright © 2016年 AA租车. All rights reserved.//import UIKitclass VIEwController: UIVIEwController { var label :UILabel! overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() // Do any additional setup after loading the vIEw,typically from a nib. label = UILabel.init(frame: CGRectMake(30,80,200,60)); label.text = "我是第一页的文字"; label.numberOflines = 0; label.textcolor = UIcolor.blackcolor(); self.vIEw.addSubvIEw(label); let btn = UIbutton.init(type: UIbuttonType.System); btn.frame = CGRectMake(60,150,50); btn.setTitle("点我跳入下一页",forState: UIControlState.normal); btn.addTarget(self,action: #selector(btnClick),forControlEvents: UIControlEvents.touchUpInsIDe); self.vIEw .addSubvIEw(btn); } //要进行传递的函数,注意参数类型及个数是否与下个页面定义的闭包函数格式相同 func changeLabelTextClosure(string: String) -> VoID { label.text = string; } func btnClick() -> VoID { let secondVC = SecondVIEwController(); //将当前changeLabelTextClosure函数指针传到第二个界面,第二个界面的闭包拿到该函数指针后会进行回调该函数 secondVC.secondVIEwControllerClosure = changeLabelTextClosure; self.presentVIEwController(secondVC,animated: true) { } } overrIDe func dIDReceiveMemoryWarning() { super.dIDReceiveMemoryWarning() // dispose of any resources that can be recreated. }}//// SecondVIEwController.swift// SwiftClosure//// Created by aayongche on 16/4/15.// copyright © 2016年 AA租车. All rights reserved.//import UIKit/* 定义一个类似于OC中的block快代码,其中第一个页面中定义的函数参数个数以及类型必须按照下面的格式, 从而确保在第一个页面定义的函数指针可以正确的传递到第二个页面, 从而使第二个页面的闭包拿到第一个页面的函数指针进行回调 */typealias TwoVIEwControllerClosure = (string :String) -> VoID;class SecondVIEwController: UIVIEwController { var secondVIEwControllerClosure :TwoVIEwControllerClosure? let secondStr = "Hello World,This is Swift Closure" overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() // Do any additional setup after loading the vIEw. self.vIEw.backgroundcolor = UIcolor.whitecolor(); let btn = UIbutton.init(type: UIbuttonType.System); btn.frame = CGRectMake(50,100,220,50); btn.backgroundcolor = UIcolor.redcolor(); btn.setTitle("点我传值到上个页面",forControlEvents: UIControlEvents.touchUpInsIDe); self.vIEw.addSubvIEw(btn); } func btnClick() -> VoID { if (secondVIEwControllerClosure != nil) { secondVIEwControllerClosure!(string: secondStr); } self.dismissVIEwControllerAnimated(true) { } } overrIDe func dIDReceiveMemoryWarning() { super.dIDReceiveMemoryWarning() // dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application,you will often want to do a little preparation before navigation overrIDe func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) { // Get the new vIEw controller using segue.destinationVIEwController. // Pass the selected object to the new vIEw controller. } */} 总结 以上是内存溢出为你收集整理的Swift中闭包实现OC的block传值全部内容,希望文章能够帮你解决Swift中闭包实现OC的block传值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)