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

时间:2017-04-09 11:07:31

标签: ios swift uitabbarcontroller ios10

我正在开发一个带有swift的iOS应用程序,其中我有一个带有5个标签栏项目的TabBarController。所有这些都指向导航控制器,然后指向视图控制器。其中一个我想显示没有标签栏的视图控制器,当用户按下取消时,它应该返回到之前选中的标签栏项/视图(之前 - 抱歉冗余)。它们都被“关系”视图控制器链接/引用“到”视图的名称“,但我没有任何特定的segue或任何东西。

这是我在 viewDidLoad 函数中调用的特定“按钮”的代码:

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
}

我尝试通过使用以下代码委派标签栏控制器来执行我想要的行为但是当选择中央按钮时,从不调用此函数(尽管正确的视图显示了......! ):

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

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

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

感谢任何帮助。

提前致谢。

1 个答案:

答案 0 :(得分:0)

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

在此图表中(它有点大 - 如果您在新标签中打开它更容易阅读),您会看到"标准" UITabBar结构。关键是放置默认"什么都不做"将控制器视为第3个选项卡,然后添加一个"特殊"查看控制器将通过代码加载:

enter image description here

然后,你的行动"功能看起来像这样:

array_2

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