Mac_Play
Mac_Play

Reputation: 302

TabbarController child controller always return nil - Swift 4

I am trying to access the objects from child controller but it always returns nil. Please check the below code.

let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc: UITabBarController = mainStoryboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
vc.selectedIndex = 2
let vc1 = vc.viewControllers?[2] as? FormViewController //this line returns nil
vc1?.fillUserData(dataDic: convertJsonStringToDictionary(jsonString: decodedURL))
vc1?.formViewDelegate = self
self.present(vc, animated: true, completion: nil)

Please shed some light.

Upvotes: 0

Views: 741

Answers (2)

rmaddy
rmaddy

Reputation: 318955

Based on your comments, the 3rd tab is actually a UINavigationController which has the FormViewController as its rootViewController.

Update your code as:

if let nc = vc.viewControllers?[2] as? UINavigationController, let vc1 = nc.topViewController as? FormViewController {
    vc1.fillUserData(dataDic: convertJsonStringToDictionary(jsonString: decodedURL))
    vc1.formViewDelegate = self
}

Upvotes: 2

Shehata Gamal
Shehata Gamal

Reputation: 100549

You can try

let nav = vc.viewControllers?[2] as? UINavigationController
let vc1 = nav?.topViewController as? FormViewController

note : you should not access any UI element here

vc1?.fillUserData(dataDic: convertJsonStringToDictionary(jsonString: decodedURL))

as it would crash the app

Upvotes: 1

Related Questions