继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

ZKReadStone
关注TA
已关注
手记 52
粉丝 32
获赞 322

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.
    }

}
打开App,阅读手记
2人推荐
发表评论
随时随地看视频慕课网APP

热门评论

您好。在firstVC中,push到secondVC,用的是"?"尝试解包,self.navigationController?。在secondVC中,pop回去,用的是"!"强制解包,self.navigationController。

对可选型这块理解不明白,可以解释一下吗?谢谢。

查看全部评论