Swift闭包函数的传值 类比OC的Block 其实是一样的
简单介绍一下代码:FirstViewController 点击按钮 push到SecondViewController,当点击Block按钮的时候回调并pop到上一页,回调的参数显示在FirstViewController的按钮上。
FirstViewController代码:
import UIKit
class FirstViewController: UIViewController {
var btn : UIButton?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.cyan
btn = UIButton(type:UIButtonType.custom)
btn!.frame = CGRect(x:40,y:80,width:120,height:35)
btn!.layer.cornerRadius = 4
btn!.layer.masksToBounds = true
btn!.backgroundColor = UIColor.lightGray
btn!.setTitle("按钮", for: UIControlState.normal)
btn!.addTarget(self, action: #selector(FirstViewController.btnClicked), for: UIControlEvents.touchUpInside)
self.view.addSubview(btn!)
}
func btnClicked() -> Void {
let second = SecondViewController()
second.callBackClosure = {
(str , name) in
self.btn!.setTitle(str, for: .normal)
}
self.navigationController?.pushViewController(second, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
SecondViewController代码:
import UIKit
typealias SwiftClosure = (String,Int) -> Void
class SecondViewController: UIViewController {
var callBackClosure:SwiftClosure?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.orange
let btn = UIButton(type:UIButtonType.custom)
btn.frame = CGRect(x:40,y:80,width:120,height:35)
btn.backgroundColor = UIColor.red.withAlphaComponent(0.4)
btn.layer.cornerRadius = 4
btn.layer.masksToBounds = true
btn.setTitle("Block按钮", for: UIControlState.normal)
btn.addTarget(self, action: #selector(SecondViewController.btnBlock), for: UIControlEvents.touchUpInside)
self.view.addSubview(btn)
}
func btnBlock() -> Void {
if callBackClosure != nil{
callBackClosure!("你的名字",26)
self.navigationController!.popViewController(animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
点击查看更多内容
2人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦