Swift 闭包(Closure)回调传值
发布时间:2020-12-14 01:55:48 所属栏目:百科 来源:网络整理
导读:实现例子由两个界面组成 A - B 使用属性传值 B - A 使用闭包进行反向回调传值 Swift 使用闭包(Closure)传值的原理,与OC 中使用代码块(block)传值原理,基本类似 按步骤可以如下理解: 1、定义闭包。 2、闭包赋值(传送) 3、闭包调用。 至于定义闭包应
实现例子由两个界面组成 Swift 使用闭包(Closure)传值的原理,与OC 中使用代码块(block)传值原理,基本类似 按步骤可以如下理解: 至于定义闭包应该在哪个页面定义? 想对于当前界面上执行某个操作,就在当前界面上定义, 实现代码: 一级界面 A : import UIKit
class ViewController: UIViewController {
var textLab:UILabel?
override func viewDidLoad() {
super.viewDidLoad()
//创建一个文本显示lab
textLab = UILabel(frame:CGRectMake(80,50,120,40));
textLab?.backgroundColor = UIColor.yellowColor();
textLab?.textAlignment = NSTextAlignment.Center;
self.view.addSubview(textLab!);
//创建一个按钮用于添加事件 A->B 属性传值
var nextBtn = UIButton(frame: CGRectMake(80,40))
nextBtn.setTitle("下一页",forState: UIControlState.Normal);
nextBtn.backgroundColor = UIColor.redColor();
nextBtn.addTarget(self,action: "nextBtnAction",forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(nextBtn);
}
//定义一个带字符串参数的闭包
func myClosure(testStr:String)->Void{
//给textLab 赋值
//这句话什么时候执行?,闭包类似于oc中的block或者可以理解成c语言中函数,只有当被调用的时候里面的内容才会执行
textLab?.text = testStr;
}
func nextBtnAction(){
//获取目标页面对象
var secondVC:SecondViewController = SecondViewController();
//属性赋值
secondVC.str = "属性传值"
//将闭包传递到二级界面,在二级界面中调用
secondVC.testClosure = myClosure;
//模态视图跳转
self .presentViewController(secondVC,animated: true,completion: nil);
}
二级界面 B : import UIKit
//类似于OC中的typedef
typealias sendValueClosure=(string:String)->Void
class SecondViewController: UIViewController {
var str:String?
//声明一个闭包
var testClosure:sendValueClosure?
override func viewDidLoad() {
super.viewDidLoad()
//创建一个文本显示lab
var textLab = UILabel(frame:CGRectMake(80,40));
textLab.backgroundColor = UIColor.yellowColor();
textLab.textAlignment = NSTextAlignment.Center;
//给文本框赋值,这个值来自上一个界面
textLab.text = str;
self.view.addSubview(textLab);
//创建一个按钮用于添加事件 B->A 闭包回调传值
var backBtn = UIButton(frame: CGRectMake(80,40))
backBtn.setTitle("返回",forState: UIControlState.Normal);
backBtn.backgroundColor = UIColor.redColor();
backBtn.addTarget(self,action: "backBtnAction",forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(backBtn);
}
func backBtnAction(){
/** 先判断闭包是否存在,然后再调用 */
if (testClosure != nil){
testClosure!(string: "回调传值")
}
self .dismissViewControllerAnimated(true,completion: nil)
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |