0

In the storyBoard "parent" scene with its parentVC.swift, there are 2 containerVC with embedded segues with their containerVC.swift for each.
In container1, a button action calls the parent custom method.

(self.parentViewController as? parentVC)?.parentCustomFunc()

which call container2 custom method.

func parentCustomFunc(){
    self.container2.customFunc()
}

I read a lot but yet to understand how to apply the use of delegate in this case.
here is my segue block as recorded in parentVC.swift

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let container1VC = segue.destinationViewController as? Cont_1 {
        self.container1 = container1VC  
    } else if let topVC = segue.destinationViewController as? TopVC {
        self.container2 = container2VC  
    }
}

Which of the containers should implement the protocol?
and which of them holds a var to it? How do I get the prepareForSegue to use the delegate?

Thanks

Fred J.
  • 5,759
  • 10
  • 57
  • 106

1 Answers1

1

You should create two protocol for each ChildViewController. Maybe like this:

protocol Child1Delegate {
     func userTapOnChild1()
}
protocol Child2Delegate {
     func userTapOnChild2()
}

And in each controller you can create instance:

var delegate: Child2Delegate!
var delegate : Child1Delegate!

At Parent controller you implement prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) to assign delegate to child:

//You get right identifier of segue you named on storyboard
if segue.identifier == "SegueChild1" {
        let controller = segue.destinationViewController as! Child1ViewController
        controller.delegate = self
    }
    if segue.identifier == "SegueChild2" {
        let controller = segue.destinationViewController as!Child2ViewController
        controller.delegate = self
    }

And when you do an action from child you can call delegate notify for Parent:

@IBAction func child1ButtonIsTapped(sender: AnyObject) {
    if let _delegate = delegate {
        _delegate.userTapOnChild1()
    }
}

Parent will implement delegate and do something need:

func userTapOnChild1() {
    let alertController = UIAlertController(title: "Child1", message: "I come from child 1", preferredStyle: .Alert)
    let action = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
    alertController.addAction(action)
    self.presentViewController(alertController, animated: true, completion: nil)
}

Detail you can reference to my demo for this case: Demo

vien vu
  • 4,277
  • 2
  • 17
  • 30