//// ViewController.swift// DelegateDemo//// Created by Jason on 1/8/18.// Copyright © 2018年 ET. All rights reserved.//import UIKitclass 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) } }}复制代码