I've added a UITabBar to my app via the interface builder and successfully linked the tabs to Tab Bar Items in other View Controllers, running the app switches between them fine. How would I go about detecting a tab has been pressed? I'd like to call a function in the selected tabs view controller class when selected. As you can probably tell I'm pretty new to swift so explanations are greatly appreciated.
I'm unable to find a recent answer for this and all answers seem to be for non-swift or a very old version of xcode.
You don't want your view controller's base class to be a UITabBarDelegate. If you were to do that, all of your view controller subclasses would be tab bar delegates. What I think you want to do is to extend UITabBarController, something like this:
class MyTabBarController: UITabBarController, UITabBarControllerDelegate {
then, in that class, override viewDidLoad and in there set the delegate property to self:
self.delegate = self
Note: This is setting the tab bar controller delegate. The tab bar has it's own delegate (UITabBarDelegate), which the tab bar controller manages, and you are not allow to change.
So, now this class is both a UITabBarDelegate (because UITabBarController implements that protocol), and UITabBarControllerDelegate, and you can override/implement those delegate's methods as desired, such as:
// UITabBarDelegate
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
print("Selected item")
}
// UITabBarControllerDelegate
func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
print("Selected view controller")
}
I'm guessing you're probably more interested in the latter. Check out the documentation to see what each of these delegates provide.
Last thing, in your storyboard (assuming you are using storyboards), set your tab bar controller's class to MyTabBarController in the Identity Inspector, and you're good to go.
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