I tried to implement a UITabBar
and now I am not able to retreive a callback from a method when an item was selected. Is there a possibillity to just create a @IBAction func
therefore? Or do I need to do something else?
Asked
Active
Viewed 1,020 times
2

nhgrif
- 61,578
- 25
- 134
- 173

Luca Archidiacono
- 127
- 2
- 16
-
possible duplicate of [Get callback/execute some code when a tab on Tab Bar is clicked](http://stackoverflow.com/questions/3667818/get-callback-execute-some-code-when-a-tab-on-tab-bar-is-clicked) – nhgrif Aug 17 '15 at 12:06
3 Answers
2
In order to implement UITabBar button, your view controller should conform to UITabBarDelegate protocol. You need to implement:
Swift:
func tabBar(_ tabBar: UITabBar, didSelectItem item: UITabBarItem!)
Objective-c:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
You also need to set the delegate (tabBar.delegate = self) in the viewDidLoad of your ViewController
Edit: Swift 3 answer:
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
}

Floris M
- 1,764
- 19
- 18
0
Your view controller should conform to UITabBarDelegate
and implement:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;
This method is called when the user selects a tab (i.e. UITabBarItem
).

Adam Waite
- 19,175
- 22
- 126
- 148
-
Do I have to call this method explicit in the code or when I implement it into the UITabBarDelegate is it going to be called automatically? – Luca Archidiacono Aug 17 '15 at 11:41
-
UITabBar will send this message to it's delegate when a user selects a tab. – Adam Waite Aug 17 '15 at 12:07
-
`class MyClass: UITabBarItem, UITabBarDelegate {` `class MyClass: UITabBar, UITabBarControllerDelegate, UITabBarDelegate {` Which of these implementations are correct? Also is this coding correct: `func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {` FYI I disconnected the default class and connected with the new customclass and it still not working (in `main.storyboard`). – Luca Archidiacono Aug 17 '15 at 12:18
-
-
A tab bar item shouldn't be the delegate to the tab bar it's on. You're probably writing yourself into a retain cycle. – nhgrif Aug 17 '15 at 12:20
-
@AdamWaite I just started programming swift 1 or 2 weeks ago so I didn't knew that I was subclassing. How can I fix this? – Luca Archidiacono Aug 17 '15 at 12:28
-
@nhgrif what do you mean with that? how should I do it else? Leave it on the default class? - I didn't understand it clearly – Luca Archidiacono Aug 17 '15 at 12:28
-
I think you need to get a book and learn the basics before anything else. – Adam Waite Aug 17 '15 at 13:24
0
I finally solved the problem. I had some trouble with the Delegator-class and normal class.
This fixed my problem : tabBar.delegate = self
in the Main-Controllerclass

Luca Archidiacono
- 127
- 2
- 16