如何将值从一个选项卡视图项传递给其他项?

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

我在“新闻”选项卡中有一个按钮,我想通过任何方式将值传递给“竞赛”选项卡。

但问题是没有传递正确的值。

我的代码是-

//新闻视图控制器

@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

    }

但我在比赛中总是犯错

图片说明-

根据每种情况尝试以下解决方案之一。

情况 1:如果您的 ViewController 嵌入在导航控制器中,请尝试以下操作:-

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

情况 2:如果您的 ViewController 没有嵌入到 navigationController

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

说明:对于第一种情况,因为您正在寻找的 VC 嵌入在 navigationController 中,那么您已经找到了它的 child,也就是您要查找的 VC寻找。对于第二种情况,没有 navigationController,因此您可以直接投射到您要查找的 VC,即.. 无需像第一种情况那样查找 child。