从 VC 展开到 TabBarController 并更改选项卡索引

Unwind from a VC to a TabBarController and change tab index

我有以下故事板布局:

当应用程序启动时,它会转到 HomeView VC TabIndex 1。

HomeView 中我有一个按钮,我使用

转到 TestView
performSegue(withIdentifier: "goToStartTest", sender: self)

现在我想从 TestView 升到 HistoryView。我现在能看到的唯一方法是创建一个从 TestViewTabBarController 的转场。这将显示 HomeView 并且标签栏完好无损。我从 TestView 开始使用

performSegue(withIdentifier: "testToRes", sender: self)

但是,我还剩下 HomeView,我需要 HistoryView

我所做的研究指出使用 Unwind 并检测 segue 的来源并采取相应的行动。

我正在使用最新的 Xcode 和 Swift 5.

要从 TestView 转到 HistoryView,应该遵循以下原则:

// From TestView to HomeView(0)
navigationController?.popViewController(animated: true)
// Change the active tab in the tabcontroller
(navigationController?.presentingViewController as? UITabBarController)?.selectedIndex = 1

像这样设置您的 HomeViewController

class HomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    var goToHistory = false

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if goToHistory {
            goToHistory = false

            // Use whichever index represents the HistoryViewController
            self.tabBarController?.selectedIndex = 1
        }
    }

    @IBAction func unwindAndGoToHistory(_ segue: UIStoryboardSegue) {
        goToHistory = true
    }
}

在您的 TestViewController 中:

  1. UIButton 连接到 Exit 图标以展开到 unwindAndGoToHistory:

  2. 通过从 View Controller 图标连接到 Exit 图标(再次选择 unwindAndGoToHistory:)创建程序化展开,然后在 Document Outline 视图并在 Attributes Inspector 中为其指定一个 标识符 ,例如 "unwindToHistory"。当你准备好继续时,使用 performSegue(withIdentifier: "unwindToHistory", sender: self).

  3. 触发它

然后,当unwind segue 被触发时,iOS 将弹出TestViewController 并调用unwindAndGoToHistory()。在那里,goToHistory 被设置为 true。之后,将触发 viewWillAppear()。由于 goToHistory 现在是 true,代码将设置 tabBarControllerselectedIndex 以切换到 HistoryViewController 的选项卡。

Note: This will show the unwind animation back to HomeViewController, then the view will automatically switch to HistoryViewController. If instead you'd like to switch to HistoryViewController immediately with no animation, override viewWillAppear instead of viewDidAppear.