Swift: How to execute an action when UITabBarItem is pressed
You should use UITabBarDelegate
with method didSelectItem
. Use it as any standard delegate:
class yourclass: UIViewController, UITabBarDelegate { func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { //This method will be called when user changes tab. }}
And do not forget to set your tab bar delegate to self
in view controller.
Here is an answer to this question
Basically you do this:
- Make sure your view controller is subscribed to the UITabBarDelegate
- Set tags in IB for each tab bar item
Implement the didSelectItem method, something like this:
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item { if(item.tag == 1) { // Code for item 1 } else if(item.tag == 2) { // Code for item 2 }}
This will give you access to each tab item tapped event. Hope it helps!
In Swift:
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { if(item.tag == 1) { // Code for item 1 } else if(item.tag == 2) { // Code for item 2 }}
SWIFT 3
class yourclass: UIViewController, UITabBarDelegate { func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { print("Test") }}
And do not forget to set your tabBar delegate to self in viewDidLoad
override func viewDidLoad(){ super.viewDidLoad() <YOUR TAB BAR NAME>.delegate = self }