Swift uses a proxy and a closure (closure) to reversely transmit values, and swiftclosure
Code of FirstViewController
Import UIKitclass FirstViewController: UIViewController, SecondViewControllerDelegate {@ IBOutlet weak var showTextLabel: UILabel! @ IBOutlet weak var showDelegateTextLabel: UILabel! Override func viewDidLoad () {super. viewDidLoad () // Do any additional setup after loading the view .} // click the button to jump to SecondViewController @ IBAction func tapGoSecondViewController (sender: UIButton) {// load SecondViewController let secondVC = UIStoryboard (name: "Main", bundle: NSBundle. mainBundle ()). instantiateViewControllerWithIdentifier ("secondViewController")! SecondViewController // implements callback to obtain the value returned by the callback.(Closure)SecondVC. backClosure = {(backStr: String)-> Void in self. showTextLabel. text = backStr} secondVC. delegate = self // jump to SecondViewController self. navigationController ?. PushViewController (secondVC, animated: true)} // MARK:-SecondViewControllerDelegate (proxy) func fetchBackString (str: String) {self. showDelegateTextLabel. text = str} override func didReceiveMemoryWarning () {super. didReceiveMemoryWarning () // Dispose of any resources that can be recreated .}}
Code of SecondViewController
Import UIKit // define the closure type (specific function type) typealias InputClosureType = (String)-> Voidprotocol Syntax: NSObjectProtocol {func fetchBackString (str: String)} class SecondViewController: UIViewController {@ IBOutlet weak var inputTextField: UITextField! // Receives the closure block var backClosure from the previous page: InputClosureType? Weak var delegate: SecondViewControllerDelegate? Override func viewDidLoad () {super. viewDidLoad () // Do any additional setup after loading the view.} @ IBAction func tapBackButton (sender: UIButton) {if self. backClosure! = Nil {if let tempString = self. inputTextField. text {self. backClosure! (TempString)} self. navigationController ?. PopViewControllerAnimated (true)} @ IBAction func delegateBackMethod (sender: UIButton) {if self. delegate! = Nil {if let tempString = self. inputTextField. text {delegate !. FetchBackString ("proxy returned data: \ (tempString)")} self. navigationController ?. PopViewControllerAnimated (true)} override func didReceiveMemoryWarning () {super. didreceivemorywarning () // Dispose of any resources that can be recreated .}}
Effect view: