【问题标题】:Pass data to Tab Bar Item (ViewController)将数据传递给标签栏项(ViewController)
【发布时间】:2018-01-24 00:43:56
【问题描述】:

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

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

self.present(plavi, animated: true, completion: nil)

此代码显示第二个选项卡视图,但没有选项卡栏以及从容器视图派生的所有内容。

【问题讨论】:

    标签: ios swift uitableview uitabbarcontroller


    【解决方案1】:

    如果你正确配置了这样的故事板,你应该通过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

    【讨论】:

    • selectedIndexPath 未在 GreenViewController 中定义,我将其定义为 'var selectedIndexPath: IndexPath = []'。我根据您的建议更改了其他所有内容,但存在一些问题。在注入函数内部,我设置了断点并得出结论,如果有条件,我永远不会在内部。这就是为什么我仍然无法切换到连接到标签栏项目的这些 ViewController 之一。
    • 你的意思是:“如果有条件,我永远不会在里面”,什么是有条件的?你的意思是这种情况:if let greenVc = self.tabBarViewController?.viewControllers?[tab.rawValue] as? GreenViewController 失败了?
    • 您是否使用调试器了解发生了什么?
    • 我也尝试过这样修复它: if let greenVc = self.tabBarViewController?.viewControllers?[1] as? FirstViewController {... 并在这一行设置断点,但我无法断定这一行有什么问题。我正在使用 swift 4 和 xcode 9
    • 我可以和你分享整个项目,我会上传到谷歌驱动器上。你还好吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2018-03-21
    • 1970-01-01
    • 2015-04-03
    • 2012-08-10
    • 2013-09-01
    • 2012-11-01
    相关资源
    最近更新 更多