Search code examples
iosuiviewcontrolleruinavigationcontrollerdelegates

Pass data before popViewController without segue and storyboard


I've got two View Controllers. Main and Temporary one. The second one performs an action on the different screen (is called by pushViewController) and then I'm popping (popViewController) and would like to present the returned value which is String.

I've tried using protocol but it's nil.

Here is my code:

SecondVC.swift:

protocol ValueDelegate {
    func append(_ text: String)
}

class SecondViewController: UIViewController{

   var delegate: ValueDelegate!

   ...

   ...
   private func function(){
      if let delegate = self.delegate{
         delegate.append(value.stringValue)
      }
      navigateBack()
   }

   private func navigateBack(){
   if let navigation = self.navigationController{
      navigation.popViewController(aniamted: true)
   }
}

MainVC.swift:

class MainViewController: UIViewController, ValueDelegate {
   var secondVC = SecondViewController()

   ...
    func append(_ value: String) {
        textField.text?.append(barcode)
    }

   ...
   override func viewDidLoad(){
      super.viewDidLoad()

      self.secondVC.delegate = self
   }
}

Solution

  • Use these links to understand exactly how to use Protocols in swift:

    You have to implement below line of code in first view controller :-

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showSecondViewController" {
            let secondViewController = segue.destination as! SecondViewController
            secondViewController.delegate = self
            }
        }