TabBar 以查看并在关闭时返回到上一个选定的视图

TabBar to view and when closed come back to previous selected view

我正在开发一个带有 swift 的 iOS 应用程序,其中我有一个带有 5 个选项卡栏项目的 TabBarController。它们都指向一个导航控制器,然后指向一个视图控制器。其中一个我想显示一个没有标签栏的视图控制器,当用户按下取消时它应该返回到之前选择的标签栏 item/view(之前 - 抱歉冗余)。它们都是 "Relationship " 视图控制器 linked/referenced 到 "name of the view",但我没有任何特定的 segue 或任何东西。

这是我在 viewDidLoad 函数中调用的特定 "button" 的代码:

func setupMiddleButton() {
    let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
    var menuButtonFrame = menuButton.frame
    menuButtonFrame.origin.y = self.view.bounds.height - menuButtonFrame.height
    menuButtonFrame.origin.x = self.view.bounds.width/2 - menuButtonFrame.size.width/2
    menuButton.frame = menuButtonFrame

    menuButton.backgroundColor = UIColor.white
    menuButton.layer.cornerRadius = menuButtonFrame.height/2

    menuButton.setImage(UIImage(named: "klein_fototoestel_2"), for: UIControlState.normal) // 450 x 450px
    menuButton.contentMode = .scaleAspectFit
    menuButton.addTarget(self, action: #selector(menuButtonAction), for: UIControlEvents.touchUpInside)

    self.view.addSubview(menuButton)


    self.view.layoutIfNeeded()
}

func menuButtonAction(sender: UIButton) {
    self.selectedIndex = 2
}

我尝试通过以下代码委派Tab Bar Controller来执行我想要的行为出现了..!):

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

    print("the selected index is : \(tabBar.items?.index(of: item))")
}

我真正想知道的是实现我想要的行为的正确方法是什么。请记住,所有视图之前都有一个 navigationController。我读到很多人建议使用 UserDefaults 来存储以前控制器的索引,但老实说,我真的认为这不合适。

感谢任何帮助。

提前致谢。

我认为你走在正确的轨道上 - 只需要获得正确的连接。

在此图中(它有点大 - 如果您在新选项卡中打开它更容易阅读),您会看到一个 "standard" UITabBar 结构。关键是将默认的 "do-nothing" 视图控制器作为第 3 个选项卡,然后添加将通过代码加载的 "special" 视图控制器:

然后,您的 "action" 函数将如下所示:

func menuButtonAction(sender: UIButton) {

    // Don't navigate to the tab index
    //self.selectedIndex = 2

    // instead, load and present the view you really want to see

    if let vc = storyboard?.instantiateViewController(withIdentifier: "SpecialVC") as? SpecialViewController {

        vc.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext

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

    }
}

您可以在此处查看并下载工作示例:https://github.com/DonMag/SWTabsWithSpecialTab