Swift那些事之-代理和闭包传值

401 阅读1分钟

//
//  ViewController.swift
//  DelegateDemo
//
//  Created by Jason on 1/8/18.
//  Copyright © 2018年 ET. All rights reserved.
//


import UIKit


class ViewController: UIViewController,ReturnValueDelegate {


    @IBOutlet weak var resultLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
    }


    @IBAction func jumpSecond(_ sender: Any) {
        let secondVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "secondViewController") as! SecondViewController
        secondVC.delegate = self
        secondVC.backClosure = {(message: String) in
            print("闭包返回的值:\(message)")
        }
        self.navigationController?.pushViewController(secondVC, animated: true)
    }
    
    func returnMessage(message: String) {
        print("代理返回的值:\(message)")
        resultLabel.text = message
    }
}

//
//  SecondViewController.swift
//  DelegateDemo
//
//  Created by Jason on 1/8/18.
//  Copyright © 2018年 ET. All rights reserved.
//


import UIKit


//闭包返回值
typealias InputClosure = (String) -> Void


//定义协议只有class级别的才能集成代理
protocol ReturnValueDelegate:class {
    func returnMessage(message:String)
}


class SecondViewController: UIViewController {
    
    @IBOutlet weak var textField: UITextField!
    weak var delegate:ReturnValueDelegate?
    var backClosure:InputClosure?
    
    @IBAction func backAction(_ sender: Any) {
        if (self.delegate != nil){
            delegate?.returnMessage(message: textField.text!)
            self.backClosure!(textField.text!)
           self.navigationController?.popViewController(animated: true)
        }
    }
}