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.
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")
}
}
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 {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With