0

My root ViewController is called MainViewController.
It has a subview called ToolsViewController.
I want to reference the subview (ToolsViewController) from my AppDelegate.

I can reference the root view, however, I cannot seem to get to the subview. I have tried the following in didFinishLaunchingWithOptions:

if let vc = window?.rootViewController as? MainViewController {
   if let toolsVC = vc.childViewControllers.first as? ToolsViewController {
      toolsVC.modelController = ModelController()
   }
}

Again, I can reference the root ViewController, but my reference to the subview is not working at all.

Thanks!

squarehippo10
  • 1,481
  • 1
  • 10
  • 33
  • Possible duplicate of [Storyboard - refer to ViewController in AppDelegate](https://stackoverflow.com/questions/8186375/storyboard-refer-to-viewcontroller-in-appdelegate) – El Tomato Jun 10 '18 at 04:16
  • @El Tomato - That link explains how to reach a view controller - not a subview of a view controller. – squarehippo10 Jun 10 '18 at 04:31
  • 1
    If you think you need to directly access a subview of a view controller from the app delegate then you are doing something wrong. Please explain why you think you need to do this. – rmaddy Jun 10 '18 at 04:33
  • I'm trying to pass state between view controllers. I'm using a "model controller" class to pass a single reference back and forth. However, the state is needed in a subview of each view controller and not the view itself. – squarehippo10 Jun 10 '18 at 04:40
  • 1
    The app delegate should call a function or set a property on the root view controller (`MainViewController`). That's it. Then `MainViewController` can act on that and pass on whatever it needs to whatever child view controller or sub view. And so on as needed until the proper subview has been notified by its owner. The App Delegate should not have any knowledge of (or care about any) possible internal structure of the root controller. – rmaddy Jun 10 '18 at 04:56
  • Interesting...and thanks. Can you tell me where this is covered? I read the UIApplicationDelegate document and most of the outdated App Programming Guide for iOS. I think there's something I'm missing... – squarehippo10 Jun 10 '18 at 05:46
  • You can pass the info in ViewDidLoad method of MainViewController. – Suhit Patil Jun 10 '18 at 07:21
  • Thanks @suhit. I’ll try that today. What I was really asking though was where are the MVC rules that cover things like an app delegate. – squarehippo10 Jun 10 '18 at 11:37
  • @squarehippo10 this answer covers it nicely https://stackoverflow.com/a/653318/1570808 and apple documentation has all covered https://developer.apple.com/documentation/uikit/uiapplicationdelegate?hl=et – Suhit Patil Jun 10 '18 at 12:04
  • It's not so much an MVC rule as it is a standard OOP concept known as [encapsulation](https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)). – rmaddy Jun 10 '18 at 15:01

0 Answers0