Search code examples
iosswiftuitabbarcontrolleruitabbar

Move to TabBar item with data using button


Hello I want to select tabbar item with some data using button on uiviewController , i can move to another tabbar using this but in this method i can't move data

let second = self.tabBarController?.viewControllers?[2] as? MyAccountViewController
second?.testValue = "Test Value"
self.tabBarController?.selectedIndex = 2

Crash Report

Could not cast value of type 'UINavigationController' (0x2496e5280) to 'xxxxxx.MyAccountViewController' (0x1016cd4c8). 2019-03-09 08:07:34.281652+0500 xxxxx[390:17926] Could not cast value of type 'UINavigationController' (0x2496e5280) to 'xxxxxx.MyAccountViewController' (0x1016cd4c8).


Solution

  • You need verify that it's the vc with

    let nav = self.tabBarController!.viewControllers![2] as! UINavigationController 
    let second = nav.viewControllers!.first as! MyAccountViewController 
    second.testValue = "Test Value"
    self.tabBarController?.selectedIndex = 2
    

    If the destination vc is not active ( first time opended ) then print the value inside viewDidLoad if it's active then print it inside viewWillAppear / viewDidAppear