将数据传递给 Tab Bar Item (ViewController) [英] Pass data to Tab Bar Item (ViewController)

查看:35
本文介绍了将数据传递给 Tab Bar Item (ViewController)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On photo below I show you my storyboard. On TableView Controller I have expandable menu. What I cannot achieve right now is to switch on second tab bar item (green one) and let it know what is ID of selected menu item. Between tab bar controller and green and blue controllers I have relationship "view controllers". I tried to call directly green view controller with this code:

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

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

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

This code displays second tab view but without tab bar and everything derived from container view.

推荐答案

如果你正确配置了这样的storyboard,你应该通过prepare(segue)UITabBarController的引用>,这样做:

If you configured correctly such storyboard, you should get the reference to the UITabBarController through prepare(segue), doing so:

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
}

此外,您可能希望声明一个枚举以干净地访问嵌入式视图控制器:

besides you may want to declare an enum to have a clean access to the embedded view controllers:

enum TabType:Int {
    case blue
    case green
}

因此您可以定义一个函数来注入选定的 indexPath,执行如下操作:

thus you might define a function for injecting the selected indexPath, doing something like:

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 调用注入:

finally whenever you have to change the current selection, you may call inject with the new indexPath:

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

<小时>

注意

调用 instantiateViewController 意味着制作一个新的假"视图控制器,这是一种错误的方法,因为您已经将它嵌入到您的 UITabBarController.viewControllers

Call instantiateViewController means making a new "fake" view controller, which is a wrong approach, since you already have it embedded in your UITabBarController.viewControllers

这篇关于将数据传递给 Tab Bar Item (ViewController)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆