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

时间:2015-01-15 20:04:20

标签: ios swift uiviewcontroller delegates protocols

我有三个视图控制器: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)
    }
}

2 个答案:

答案 0 :(得分:0)

您还需要在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实现两种协议。

答案 1 :(得分:0)

您可以使用键值观察或NSNotifications。