2

I used this code here to pass data from first view controller to the second view controller

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? secondViewController {
        vc.showPageType = self.checkEdit
   }

But the problem is that in the second view controller I have text field that when user fill that text field and push the button submit the secondViewController will be dismiss with this method

dismiss(animated: false, completion: nil)

and now I can't use perform segue method to pass textfield text to the first view controller how can I do that in swift4?

7
  • 1
    Use delegates to pass data from B->A. Commented Dec 24, 2017 at 8:58
  • 1
    Possible duplicate of How to pass data to another controller on dismiss ViewController? Commented Dec 24, 2017 at 9:17
  • there is a problem my firstviewcontroller is a tableviewcontroller not view controller Commented Dec 24, 2017 at 9:21
  • That's not a problem , tableviewcontroller is a sub class of UIViewController. Commented Dec 24, 2017 at 9:23
  • ok so in that question where should I write protocol in the view controller or table view controller ? Commented Dec 24, 2017 at 9:24

1 Answer 1

2

Add to your secondViewController source code file:

protocol SecondViewControllerDelegate {

    func submitButtonPushedWithText(_ text: String)
}

Add to class secondViewController property:

var delegate: SecondViewControllerDelegate?

Then conform your first controller to SecondViewControllerDelegate and implement method submitButtonPushedWithText(:):

class FirstViewController: UIViewController, SecondViewControllerDelegate {

    func submitButtonPushedWithText(_ text: String) {
        // use text from textField of second controller 
    }
}

Also setup delegate property of second controller before presenting:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? secondViewController {
    vc.showPageType = self.checkEdit
    // setup delegate
    vc.delegate = self
}

Now you can call method submitButtonPushedWithText(_ text: String) in your Second controller just before calling dismiss(animated: false, completion: nil):

func submitButtonPushed() {
    delegate?.submitButtonPushedWithText(textField.text!)
    dismiss(animated: false, completion: nil)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.