Sending data between viewControllers using protocol+delegate in swift 4

I'm a beginner with Swift and I'm struggling to understand the way the variables are send between page_1 and page_2 using delegate and protocols.

I have a 2-page application: ViewController1.swift and ViewController2.swift - on page 1 (ViewController1.swift) I have a textbox (TextBoxControl) and a button. - on page 2 (ViewController2.swift) I have a label and a button

I want to send text in thextbox from page_1 to page_2 and print it in page_2.

The problem is that the delegated is always nil (it prints on the console ... print ("Delegate is nil"). )

Technologies: XCODE Version 9.4.1, swift 4

How can I solve this?

Thanks in advance.

1 answer

  • answered 2018-07-12 07:29 Sanjukta

    If you want send data from ViewController1 to ViewController2 then simply follow these step.

    Step 1:

    Set a variable in ViewController2 : like

    var strValue : String?
    

    step 2:

    Write this code in button action ViewController1

    let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    let destination = storyboard.instantiateViewController(withIdentifier: "ViewController2") as! ViewController2
    destination.strValue = yourTextBoxControl.text
    self.navigationController?.pushViewController(destination, animated: true)
    

    step 3:

    In ViewController2 class you can easily get this value like :

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

    Thanks hope it will helps you.