Reputation: 302
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
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
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