-2

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
   }
}
mikro098
  • 2,173
  • 2
  • 32
  • 48

2 Answers2

1

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
        }
    }
Amit
  • 4,837
  • 5
  • 31
  • 46
1

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

Because you never set it to anything. It was your job, when you pushed the SecondViewController, to set its valueDelegate to the MainViewController. But you didn't.

What you did do was set the valueDelegate of another SecondViewController to the MainViewController:

var secondVC = SecondViewController()
self.secondVC.delegate = self

That was silly, because secondVC is a different, newly made instance of SecondViewController having nothing at all to do with your real interface. In particular, it is not the SecondViewController instance that gets pushed. But that is the instance you need to set the delegate of.

matt
  • 515,959
  • 87
  • 875
  • 1,141