简体   繁体   English

标签栏项目作为按钮

[英]Tab bar item as button

I have 5 tab bar items in my tab bar, 4 of which have segues to navigation controllers which lead to view controllers.我的标签栏中有 5 个标签栏项目,其中 4 个有导航控制器的 segue,这些导航控制器通向视图控制器。 I want to make the middle tab bar item act as a button, so that when I click on it, I have control over what happens.我想让中间的标签栏项目充当一个按钮,这样当我点击它时,我就可以控制发生的事情。

Currently, my middle tab bar item is also connected to a navigation controller, which is not right because now when I click the tab bar item, it opens a black navigation controller.目前,我的中间标签栏项目也连接到导航控制器,这是不对的,因为现在当我单击标签栏项目时,它会打开一个黑色的导航控制器。 How can I convert the middle tab bar item to act as a button, rather than going to a navigation controller?如何将中间选项卡栏项转换为按钮,而不是转到导航控制器?

If I remove the navigation controller, it also removes the tab bar item from the tab bar.如果我删除导航控制器,它也会从选项卡栏中删除选项卡栏项目。

If you want your tab bar item to act as a button you could subclass a UITabBarController and implement this delegate function:如果你希望你的标签栏项目作为一个按钮,你可以继承一个UITabBarController并实现这个委托函数:

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {

        // Check if bar item selected is center
        if viewController.tabBarItem.tag == 2 {


            // Do Something Here ...


            // Present View Controller
            guard let navigationController = storyboard?.instantiateViewController(withIdentifier: "NavigationController") as? UINavigationController else { return false }

            present(navigationController, animated: true)

            // Returning false will not open the connected tab bar item view controller you attached to it
            return false

        }

        // Return true to open the connected tab bar item view controller you attached to it (e.x. everything but the center item)
        return true
    }

To implement a custom tab bar and use tab bar items like a normal button实现自定义标签栏并像普通按钮一样使用标签栏项目

  1. Add a new Tab Bar view to your view controller (VC)将新的 Tab Bar 视图添加到您的视图控制器 (VC)
  2. Add the custom tab bar items you need and assign tag numbers on them (On Attribute inspector)添加您需要的自定义标签栏项目并为其分配标签编号(在属性检查器上)
  3. Add a delegate outlet from Tab bar View to your view controller (Right Click and drag To VC)将 Tab bar View 中的委托出口添加到您的视图控制器(右键单击并拖动到 VC)
  4. On your view controller, subclass UITabBarDelegate, like this在你的视图控制器上,子类 UITabBarDelegate,像这样
class ViewController: UIViewController, UITaBarDelegate {}
  1. Implement this delegate function, then it should works实现这个委托功能,那么它应该可以工作
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { if item.tag == 1 { //Do something } if item.tag == 2 { //Do something } ....... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM