以编程方式在子视图中切换选项卡栏视图(自定义选项卡栏控制器)

时间:2016-11-13 05:02:33

标签: ios swift uitabbarcontroller uitabbar

因为我想重新设计标签栏UI,我根据https://github.com/codepath/ios_guides/wiki/Creating-a-Custom-Tab-Bar编写了一个自定义标签栏控制器

TabBarViewController的viewDidLoad()中,定义与每个标签栏对应的多个子视图

homeViewController = storyboard.instantiateViewControllerWithIdentifier("HomeViewController")
...
viewControllers = [homeViewController, searchViewController, accountViewController, trendingViewController]

和点击标签的主要方法

@IBAction func didPressTab(_ sender: UIButton) {

        let previousIndex = selectedIndex
        selectedIndex = sender.tag

        tabButtons[previousIndex!].isSelected = false
        let previousVC = viewControllers[previousIndex!]

        // remove previous VC
        previousVC.willMove(toParentViewController: nil)
        previousVC.view.removeFromSuperview()
        previousVC.removeFromParentViewController()

        // set current VC
        sender.isSelected = true
        let vc = viewControllers[selectedIndex]

        addChildViewController(vc)

        // Adjust the size to match content view
        vc.view.frame = contentView.bounds
        contentView.addSubview(vc.view)
        vc.didMove(toParentViewController: self)
    }

我可以在加载标签栏视图时设置默认标签栏索引selectedIndex。但是,如何在homeViewController中切换到下一个标签栏(不点击标签栏按钮)?

这不适用于homeViewController TabBarViewController().tabButtons[2].isSelected = true TabBarViewController().didPressTab(TabBarViewController().tabButtons[2])

我不确定如何在子视图控制器中获取正在运行的选项卡控制器,设置selectedIndex和更新子视图。

2 个答案:

答案 0 :(得分:0)

您需要做的就是调用tabBar.setSelectedViewController:并传递视图控制器。

如果您只知道选项卡索引,则调用tabBar.viewControllers [index]并获取视图控制器。

答案 1 :(得分:0)

我最终使用Delegate来解决。

在SubViewController中添加协议

protocol SubViewControllerDelegate {
    func transferToView(index: Int)
}

并在课堂上声明这个

var delegate: SubViewControllerDelegate?

在TabBarViewController中设置为符合SubViewControllerDelegate

实施方法

func transferToView(index: Int) {
    tabButtons[index].isSelected = true
    didPressTab(tabButtons[index])
}

设置代理

subViewController = storyboard.instantiateViewControllerWithIdentifier("HomeViewController")
let subVC = subViewController as! SubViewController
subVC.delegate = self