为了账号安全,请及时绑定邮箱和手机立即绑定

iOS学习笔记--Swift之闭包函数的传值

标签:
iOS

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人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
32
获赞与收藏
322

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消