Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create uitabbar item on swift without a View Controller lined to it

So my problem is I'm creating a UITabBarController without a storyboard and I'm stuck with how to create a UITabBar item without a Viewcontroller. Because what I want to do is the 2nd item of my UITabBarItem is an action not presenting a view controller.

like image 902
Desmond A Avatar asked Aug 21 '17 14:08

Desmond A


2 Answers

I implement something like this in an app (the close button), though I use storyboards. The close button is a viewController, but I used the following code to get it to act like a regular button:

 func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
    // this provides UI feedback that the button has been pressed, even though it leads to the dismissal
        if viewController == self.viewControllers![4] {

           viewController.tabBarItem.image? = UIImage(named: "TabBarClose")!.imageWithColor(UIColor.red).withRenderingMode(UIImageRenderingMode.alwaysOriginal)

            return false
        } else {
        return true
        }
    }

override func viewDidDisappear(_ animated: Bool) {
//sets the close button back to original image
    self.viewControllers![4].tabBarItem.image = UIImage(named: "TabBarClose")!
}

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
// this is so it never actually goes to the close buttons viewController
    currentTab = self.selectedIndex != 4 ? self.selectedIndex:currentTab
    saveTabIndexToPreferences(currentTab!)

}

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    // assign functionality to the close button
    if item.tag == 100 {// this is old code, there is probably a better way to reference the tab
        dismissTabBar()
    } else {

    }        
}

EDIT (for a question that was asked)

func selectTabIndexFromPreferences() {
    let defaults:UserDefaults = UserDefaults.standard
    selectedIndex = defaults.integer(forKey: "songSelectionTabIndex_preference")
}

func saveTabIndexToPreferences(_ index:Int?) {
    if index != nil {
        let defaults:UserDefaults = UserDefaults.standard
        defaults.set(index!, forKey: "songSelectionTabIndex_preference")   
    }
}

tab-bar close button

like image 103
solenoid Avatar answered Nov 16 '22 23:11

solenoid


If you really want to do this (it's pretty nonstandard UI...), then you could add an empty view controller, but in your tab bar delegate implement

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

}
like image 32
Abdelahad Darwish Avatar answered Nov 17 '22 01:11

Abdelahad Darwish