Curtain Call LLC
Curtain Call LLC

Reputation: 144

Pass data from Modal view to Parent view using delegates (with a segue in storyboard)

I am trying to pass some data from one view to the next, however I am using a segue (using storyboard to do this) in order to open the second view in Modal presentation.

And now I am using delegates to pass some information from the open modal window back to the home view...

It doesn't work, it never reaches the main window. Doesn't crash.

I tried using this: Inserting rows to tableView using modal popup (which is actually what I am trying to accomplish) but I was not able to make it work. I am also missing the part where it says

myPopUp.delegate = self 

since I am using a segue through storyboard and I do not have a way to do this...

Please help!


This is the main controller:

import UIKit

class HomeViewController: UIViewController, AddRowDelegate {
    public func didAddRow(name: String){
        print("reached HomeViewController") // This does NOT print
    }

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

And this is the Modal Window:

import UIKit

protocol AddRowDelegate {
    func didAddRow(name : String)
}

class ModalViewController: UIViewController {

    var delegate : AddRowDelegate?

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

    @IBAction func SendInfoBack(_ sender: Any) {
        delegate?.didAddRow(name: "whatever")
        print("Modal Window") // This part DOES print.
    }
}

Upvotes: 1

Views: 1188

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

In prepareForSegue set delegate

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

Upvotes: 3

Negar Moshtaghi
Negar Moshtaghi

Reputation: 463

If i understand your question right you should the same data type at destination view and pass it through the prepare function

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toTabBar"{
        let destView = segue.destination as! UIView
        destView.data= dataToPass
    }
}

.

Upvotes: 1

Related Questions