Ios 将数据传递到选项卡栏项(ViewController)

Ios 将数据传递到选项卡栏项(ViewController),ios,swift,uitableview,uitabbarcontroller,Ios,Swift,Uitableview,Uitabbarcontroller,在下面的照片上,我向你们展示了我的故事板。在TableView控制器上,我有可展开的菜单。我现在无法实现的是打开第二个选项卡栏项(绿色的),让它知道所选菜单项的ID是什么。在选项卡栏控制器和绿色和蓝色控制器之间,我有“视图控制器”的关系。我试图用以下代码直接调用green view controller: let secondTab = self.storyboard?.instantiateViewController(withIdentifier: "secondstoryboardid")

在下面的照片上,我向你们展示了我的故事板。在TableView控制器上,我有可展开的菜单。我现在无法实现的是打开第二个选项卡栏项(绿色的),让它知道所选菜单项的ID是什么。在选项卡栏控制器和绿色和蓝色控制器之间,我有“视图控制器”的关系。我试图用以下代码直接调用green view controller:

let secondTab = self.storyboard?.instantiateViewController(withIdentifier: "secondstoryboardid") as! SecondVC

self.present(plavi, animated: true, completion: nil)
此代码显示第二个选项卡视图,但没有选项卡栏和从容器视图派生的所有内容


如果您正确配置了这样的故事板,您应该通过
prepare(segue)
获得对
UITabBarController
的引用,这样做:

private weak var tabBarViewController:UITabBarController?

// be sure to add prepare inside your segue manager (the container in this case)
override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    self.tabBarViewController = segue.destination as? UITabBarController
}
此外,您可能希望声明一个枚举,以便对嵌入式视图控制器具有干净的访问权限:

enum TabType:Int {
    case blue
    case green
}
因此,您可以定义一个函数来注入选定的indexPath,执行如下操作:

func inject(indexPath:IndexPath, into tab:TabType) {
    if let greenVc = tabBarViewController?.viewControllers?[tab.rawValue] as? GreenViewController {
        greenVc.selectedIndexPath = indexPath
        tabBarViewController?.selectedIndex = tab.rawValue // this will auto select the TabType viewcontroller
    }
}
最后,无论何时需要更改当前选择,都可以使用新的indexPath调用inject:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.inject(indexPath: indexPath, into: .green)
}

注意


调用
InstanceViewController
意味着创建一个新的“假”视图控制器,这是一种错误的方法,因为您的
UIAbbarController中已经嵌入了它。ViewController

selectedIndexPath未在GreenViewController中定义,我将其定义为“var selectedIndexPath:IndexPath=[]”。其他一切我都按照你的建议做了改变,但有一些问题。在注入函数中,我设置了断点,并得出结论,如果条件满足,我永远不会在函数中。这就是为什么我仍然无法切换到这些连接到选项卡栏项的ViewController中的一个。您的意思是:“如果有条件,我永远不会在里面”,什么是条件?您的意思是:
如果让greenVc=self.tabBarViewController?.viewControllers?[tab.rawValue]as?GreenViewController
失败?您是否使用调试器了解发生了什么?我也尝试这样修复它:如果让greenVc=self.tabBarViewController?.ViewController?[1]作为?FirstViewController{…并将断点放在这一行上,但我无法断定这一行有什么问题。我使用的是swift 4和xcode 9I,我可以与您共享整个项目,我会将其上传到google drive上。对您合适吗