使用选项卡栏控制器时,按钮是否可以打开到特定选项卡?

Is it possible for a button to open into a specific tab when using the Tab Bar Controller?

这个问题表达起来有点混乱,所以希望图片会更有帮助。这是设置:

所以,我想要 First View 按钮打开 FirstViewController,我想要 Second View 按钮打开SecondViewController。如果我 link 第二视图 按钮到 SecondViewController 像这样:

我失去了标签导航。如果我像这样将按钮连接到 TabViewController

然后会自动打开成FirstViewController。除非我遗漏了什么,否则这似乎需要一些额外的代码来完成,但我似乎找不到任何解释如何执行此操作的内容。

谢谢!

使用标识符创建从 ViewcontrollerTabBarController 的故事板转场。然后在prepareforsegue方法

中分配TabBarController的selelctedIndex

@IBAction func firstBtnAction(_ sender: Any) {
    (sender as! UIButton).tag = 0
    performSegue(withIdentifier: "tabBar", sender: sender)
}
@IBAction func secBtnAction(_ sender: Any) {
    (sender as! UIButton).tag = 1
    performSegue(withIdentifier: "tabBar", sender: sender)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "tabBar" {
        if let vc = segue.destination as? UITabBarController {
            vc.selectedIndex = (sender as! UIButton).tag
        }
    }
}

在tabViewController中你需要实现以下功能..

var index : Int!

@IBAction func button1(_ sender: Any) {
        index = 1
        self.performSegue(withIdentifier: "TabBarSegue", sender: self)
}

@IBAction func button2(_ sender: Any) {
        index = 2
        self.performSegue(withIdentifier: "TabBarSegue", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if(segue.identifier == "TabBarSegue"){
            let videoController : TabBarController = segue.destination as! TabBarController
            videoController.index = index
}

然后你需要实现TabBarController并实现以下..

import UIKit

class TabBarController: UITabBarController {

    var index : Int!


    override func viewDidLoad() {
        super.viewDidLoad()

        selectedIndex = index

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}