简体   繁体   中英

How to get parent of child view controller?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM