How can I segue to the second tab of a tab bar controller from the first tab?

放肆的年华 提交于 2019-11-29 04:20:26

You don't want to segue. A segue creates a new instance of the destination view controller and presents it.

That's why your tab bar is disappearing. You are covering your tab bar controller, with it's 2 tabs, with a new instance of your TabBarController2.

You want to switch to the other tab.

What you want to do is to ask your owning tab bar controller to switch tabs.

UIViewController has a property tabBarController that lets you get to your owning tab bar controller.

TabBarControllers have a property selectedIndex that let you select one of a tab bar controller's view controllers to become the active view controller.

So, send a message to your tab bar controller asking it to switch to the other tab.

EDIT:

Other people aside from the OP have asked for sample code illustrating how to do this. I decided to create a sample project illustrating how to do it.

You can download it from Github: https://github.com/DuncanMC/TabBarControllers.git

I created a base class of UIViewController ATabController for the view controllers that are managed by the tab bar controller. The ATabController.swift file includes an enum to indicate which tab you want to select:

@objc enum Tab: Int {
  case first = 0
  case second
  case third
}

(Note that the enum has to be an Objective-C enum if you're going to pass parameters of type Tab to IBActions, since IBAction methods need to use Objective-C types and function signatures.)

It also includes a protocol TabController:

@objc protocol TabController {
  @objc func switchTab(to: Tab)
}

It also defines a delegate tabDelegate:

weak var tabDelegate: TabController?

The tab bar controller has a prepareForSegue (prepare(for:sender:)) that it uses to make itself the tabDelegate of all the view controllers it manages as tabs:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if let child = segue.destination as? ATabController {
    child.tabDelegate = self
  }

And then it implements the switchTab(to:) method:

@objc func switchTab(to: Tab) {
  let index = to.rawValue
  guard let viewControllerCount = viewControllers?.count,
    index >= 0 && index < viewControllerCount  else { return }
  selectedIndex = index
}

In any of the child view controllers that are tabs of the tab bar controller, you can use IBAction code like this to switch tabs:

@IBAction func handleFirstButton(_ sender: Any) {
  tabDelegate?.switchTab(to: .first)
}

If you're looking for how to change from one tab to another in a tab controller without using the tab bar you can do this

tabBarController?.selectedIndex = [number of tab]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!