Search code examples
swiftuitabbar

How to pass value from one tabbar View item to other?


I have a button in News Tab, And I want pass value to Competition Tab by any way.

But the problem is not passing correct value.

My code is-

//NewsViewController

@IBAction func fullStndngAction(_ sender: Any) {
        //I Tried this
        let prefs = UserDefaults.standard
        prefs.set(true, forKey: "isFromNewsView")

        //I Tried This as well
        let whereFrom  = storyboard?.instantiateViewController(withIdentifier: "LatestNewsDetailViewController") as? LatestNewsDetailViewController
        whereFrom!.isFromNewsView = true

        self.tabBarController?.selectedIndex = 1

    }

But always I am getting false in competition view.

Image description-

enter image description here


Solution

  • Try one of the following solutions depending on each condition.

    case 1: If your ViewController is embedded in a navigationController try this: -

    if let competitionsVC = self.tabBarController.viewControllers?[1].children.first as? CompetitionViewController {
     competitionVC.isFromNewsView = true
     self.tabBarController?.selectedIndex = 1
    }
    

    Case 2: If your ViewController is not embedded in navigationController

    if let competitionVC = self.tabBarController.viewControllers?[1] as? CompetitionViewController {
     competitionVC.isFromNewsView = true
     self.tabBarController?.selectedIndex = 1
    }
    

    Explanation: For case one since the VC which you are looking for is embedded in navigationController then you have cast down the way to it's child which is the VC you are looking for. For case two there is no navigationController so you cast direct to the VC you are looking for, ie.. no need to find child like on case 1.