如何使用回调将数据发送回以前的ViewController

时间:2016-03-29 15:35:47

标签: swift

我有2个像这样的ViewControllers:

enter image description here

我想在ViewController中按下按钮时会显示给ViewController2。然后当我在TextField中输入文本并按下ViewController2中的Back Button时,会将该文本发送到ViewController1中的按钮。

我可以使用委托或使用ViewController2中的ViewController类来解决这个问题。 (你可以看看我的评论代码)

但现在我想使用CallBack发回数据。

如何做到这一点:

这是ViewController:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var button: UIButton!
    var myString = ""

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(animated: Bool) {
        button.setTitle(myString, forState: .Normal)
    }
    @IBAction func goToViewController2(sender: AnyObject) {
        let vc2 = storyboard?.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2
//        vc2.vc1 = self
        presentViewController(vc2, animated: true, completion: nil)
    }
}

和ViewController2:

import UIKit

class ViewController2: UIViewController, UITextFieldDelegate {

    @IBOutlet var textField: UITextField!
//    var vc1: ViewController?
    var callback: ((String) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    func textFieldDidEndEditing(textField: UITextField) {
        callback!(textField.text!)
    }

    @IBAction func backToViewController(sender: AnyObject) {
//        vc1?.myString = textField.text!
        dismissViewControllerAnimated(true, completion: nil)
    }
}

我不想在解除功能中使用完成块,我只想使用自己的回调方法。

1 个答案:

答案 0 :(得分:2)

vc1中,在显示之前设置vc2的回调属性:

@IBAction func goToViewController2(sender: AnyObject) {
    let vc2 = storyboard?.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2
    vc2.callback = { <Put your callback code here...> }
    presentViewController(vc2, animated: true, completion: nil)
}

然后,在vc2中,在解除视图控制器之前调用回调函数:

@IBAction func backToViewController(sender: AnyObject) {
    callback?(textfield.text!)
    dismissViewControllerAnimated(true, completion: nil)
}