简体   繁体   中英

Calling func of another view controller to control alpha returns nil error

I have a (parent) view controller that has a container view within it. When app is started, it first goes to the parent, then it goes into the container view. Within the container view controller I try something like parentName().changeAlpha() - this is a function belonging to the parent... which should change the alpha of a label on the parent view.

However, it keeps giving me a nil error as soon as I attempt to call that function. Please keep in mind the parent view is being loaded first thing.

Hierarchy: (I have the Xcode name of each controller followed by the file name belonging to it in parenthesis)

Tab Bar Controller (TabBarController) (There are 3 tabs)

Tab1 (homeScreenContainer) - Contains a view controller with a uiviewcontainer within it. Also contains the function that I am trying to call.

All part of container view:

  • Page View Controller (2 Pages total, first page is the one below) (RootPageViewController)

    • View controller (ViewController) - this is where I am trying to call the function.

Tab2 (Irrelevant)

Tab3 (Irrelevant)

Also, the only inheritance in both the code and the storyboard is only the uiviewcontainer (and there is no code inheritance involved there).

Doing this

parentName().changeAlpha()

Creates another object of parent other than the shown one , and it gives nil error as the VC should be loaded from Stroyboard/Xib not like this parentName() except if it's programmatically created , what you really need is querying the window for it , suppose the parent is the rootVC of the window you can do this

if let tab = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController {
      print("Inside Tap")
   if let realParent = tab.viewControllers![0] as? ParentVC {
     print("Inside Parent")
     realParent.changeAlpha()
   }
}

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