使用后退按钮将数据从 ThirdViewController 传递到 FirstViewController

Passing Data From ThirdViewController to FirstViewController Using the Back Button

我有三个视图控制器:FirstViewController 有两个标签,SecondViewController 只有一个文本字段,ThirdViewController 也有一个文本字段。我想要做的是从第二个和第三个视图控制器传回数据。我能够将数据从第二个传递到第一个,但我无法从第三个传递回第一个。任何帮助将不胜感激。

仅供参考,我正在使用故事板。

FirstViewController

class FirstViewController: UIViewController, AcceptDataFromSecondVC, AcceptedDataFromThirdVC{

    @IBOutlet weak var dataFromSecond: UILabel!
    @IBOutlet weak var dataFromThird: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func acceptDataFromSecond(data: String) {

        dataFromSecond.text = data
    }

    func acceptedDataFromThird(data: String) {

        dataFromThird.text = data
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SecondSegue" {
        var secondVC = segue.destinationViewController as SecondViewController
        secondVC.delegate = self
    }

}

}

SecondView 控制器

protocol AcceptDataFromSecondVC {

    func acceptDataFromSecond (data : String)
}

class SecondViewController: UIViewController {

    var delegate : AcceptDataFromSecondVC?

    @IBOutlet weak var dataToSend2: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    override func viewWillDisappear(animated: Bool) {

        delegate?.acceptDataFromSecond(dataToSend2.text)
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    var thirdVC = segue.destinationViewController as ThirdViewController
    thirdVC.delegate = self.delegate as AcceptedDataFromThirdVC

}

}

ThirdViewController

protocol AcceptedDataFromThirdVC {

    func acceptedDataFromThird (data : String)
}

class ThirdViewController: UIViewController {

    var delegate : AcceptedDataFromThirdVC?

    @IBOutlet weak var dataToSend3: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

    }
    override func viewWillDisappear(animated: Bool) {

        self.delegate?.acceptedDataFromThird(dataToSend3.text)
    }
}

您还需要在 ThirdViewController 上设置委托,就像您为 SecondViewController 所做的那样。

如果它是从 FirstViewController 启动的,您可以使用:

var thirdVC = segue.destinationViewController as ThirdViewController
thirdVC.delegate = self

如果它是从 SecondViewController 启动的,您可以使用:

var thirdVC = segue.destinationViewController as ThirdViewController
thirdVC.delegate = self.delegate as AcceptedDataFromThirdVC

确保 FirstViewController 实施这两个协议。

您可以使用 Key Value Observing 或 NSNotifications。