简体   繁体   中英

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. 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:

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)
  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)
  4. On your view controller, subclass UITabBarDelegate, like this
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 } ....... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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