首页 » Swift » Swift3.0 闭包

Swift3.0 闭包

原文 http://blog.csdn.net/weixin_40166364/article/details/77914165

2017-09-09 14:20:25阅读(560)

闭包 –> 逆向传值

SecondViewController控制器

import UIKit
class SecondViewController: UIViewController {
import UIKit
class SecondViewController: UIViewController {
    // ***** 注意 *****
    // 声明闭包的时候  必须对闭包进行初始化 = {}  否则闭包会一直为nil
    var callBack:((Int)->())? = {
        value in
    };
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        let btn = UIButton()
        btn.setTitle("返回", for: .normal)
        btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        btn.backgroundColor = UIColor.purple
        btn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
        self.view.addSubview(btn)
    }
    func backBtnClick() {
        if self.callBack != nil { // 判断闭包不为空的时候将值传递出去
            self.callBack!(123);
            self.navigationController?.popViewController(animated: true)
        }
    }
}

FirstViewController控制器

import UIKit
class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        let btn = UIButton()
        btn.setTitle("跳转", for: .normal)
        btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        btn.backgroundColor = UIColor.purple
        btn.addTarget(self, action: #selector(pushBtnClick), for: .touchUpInside)
        self.view.addSubview(btn)
    }
    func pushBtnClick() {
        let secondVC = SecondViewController()
        secondVC.callBack = { // 获取call回来的值
            value in
            print(value,"value....")
        }
        self.navigationController?.pushViewController(secondVC, animated: true)
    }
}
好了,简单学会了闭包

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹