Swift使用闭包(closure)进行界面间的反向传值

直接上代码

import UIKit

class ViewController: UIViewController {

    let btn: UIButton! = UIButton(type: UIButtonType.Custom)
    override func viewDidLoad() {
        super.viewDidLoad()
        createBtn()
    }

    func createBtn() {
        btn.frame = CGRect(x: 100, y: 200, width: 80, height: 80)
        btn.backgroundColor = UIColor.blackColor()
        btn.setTitle("第一界面", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.addTarget(self, action: #selector(goSecondPage), forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(btn)
    }
    
    func goSecondPage() {
        let secondVC = MSecondViewController()
        self.presentViewController(secondVC, animated: true) {
            //将当前takeClosure函数指针传到下一界面, 第二个界面的闭包拿到该函数指针后回调该函数
            secondVC.initClosure(self.takeClosure)
        }
    }
    
    // MARK: 函数指针
    func takeClosure(string: String) -> Void {
        //拿到返回的值
        btn.setTitle(string, forState: UIControlState.Normal)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
import UIKit

//类似Objective-C的typedef
typealias postClosure = (string: String) -> Void
class MSecondViewController: UIViewController {

    //声明个闭包
    var MClosure: postClosure?
    
    //传入上个界面的takeClosure函数指针
    func initClosure(closure: postClosure?) {
        //将函数指针赋值给MClosure闭包,此闭包包含takeClosure的局部变量等引用
        MClosure = closure
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.greenColor()
        createBack()
    }
    
    func createBack() {
        let btn: UIButton! = UIButton(type: UIButtonType.Custom)
        btn.frame = CGRect(x: 100, y: 200, width: 80, height: 80)
        btn.backgroundColor = UIColor.blackColor()
        btn.setTitle("返回", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.addTarget(self, action: #selector(goBack), forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(btn)
    }
    
    func goBack() {
        self.dismissViewControllerAnimated(true) { 
            if self.MClosure != nil {//判断是否为空
                //回调:闭包隐式调用takeClosure函数
                self.MClosure!(string: "反向传值")
            }
        }
    }
}
Swift使用闭包(closure)进行界面间的反向传值_第1张图片
Paste_Image.png
Swift使用闭包(closure)进行界面间的反向传值_第2张图片
Paste_Image.png
Swift使用闭包(closure)进行界面间的反向传值_第3张图片
Paste_Image.png

你可能感兴趣的:(Swift使用闭包(closure)进行界面间的反向传值)