How to get parent of child view controller?

1.4k Views Asked by At

I have a view controllerA with segmented control, and I have added two view controller's(B & C) views in controllerA on different segment selection.I have one button each on controllerB and controllerC.On button click of each controllerB & controllerC, I am going to controllerD.

How do I know from which controller I am coming from?

I have tried code below but I think due to views of controller's (B & C) added to controllerA, it is giving me nil.

guard let parent = self.parent else {return}

How to get parent in this scenario?

1

There are 1 best solutions below

4
Asim On

A slightly different solution I used once:

  • Declare an enum with sender A, B, C etc.

    enum Sender {
        case A
        case B
        case C
    }
    
  • Put a variable in D called sender.

     var sender : Sender!
    
  • On initializing VC set it's respective sender. If you are using segue use prepare for segue to set value.

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        if segue.identifier == "D" {
            let vc = segue.destination as! D
            vc.sender = B or C //As required
        }
    }
    

Then you can use the value of sender to do what ever you want based on the sender. The good thing here is if you keep navigating you can always propagate the sender value to next ViewControllers.