如果你正确配置了这样的故事板,你应该通过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 调用注入:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.inject(indexPath: indexPath, into: .green)
}
注意
调用instantiateViewController 意味着制作一个新的“假”视图控制器,这是一种错误的方法,因为您已经将它嵌入到您的UITabBarController.viewControllers 中