Search code examples
swiftsegueprotocolsdelegation

How to achieve delegation between two ViewController use segue in swift?


enter image description here

I am little bit confuse abt delegation in swift. Say, if I want to pass text of textfield in BViewController to AViewController. (AViewController has a label but I did not put any text, so it shows nothing there) After user done the input and click the "LETS GO" button, text of label in AViewController should show the same text. I implement the code but it gives me some errors. Thanks.

code:

import UIKit

class AViewController: UIViewController, BViewDelegate {


    @IBOutlet weak var labelTextData: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()


    }

    func userDoneInput(textData: String) {
        labelTextData.text = textData
    }



}




import UIKit

protocol BViewDelegate{
    func userDoneInput(textData: String)
}

class BViewController: UIViewController {


    @IBOutlet weak var UserInputText: UITextField!
    var bViewDelegate: BViewDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()


    }


    @IBAction func LetsGo(_ sender: UIButton) {
       self.performSegue(withIdentifier: "ShowData", sender: self)

    }

    //use segue
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier  == "ShowData" {
            let destination = segue.destination as! AViewController
            destination.labelTextData.text = UserInputText.text

        }
    }

}

Solution

  • 1- A shows

    2- When you perform segue to B set delegate here ( this code inside A )

    @IBAction func MoveToB (_ sender: UIButton) {
       self.performSegue(withIdentifier: "GoToB", sender: self)
    
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier  == "GoToB" {
            let destination = segue.destination as! BViewController
            destination.bViewDelegate = self
        }
    }
    

    3- When you want to return from B to A ( This code inside B )

    self.bViewDelegate?.userDoneInput(textData: UserInputText.text!)
    self.dismiss(animated:true,completion:nil)
    

    4- There should not be any segue from B to A