Search code examples
iosswiftuitabbaruitabbaritem

How to detect when pressing down on UIBarButtonItem?


I want to implement a scale animation when the user presses down on a UITabBarItem. How can I detect when a tabBarItem in a tabBar is being pressed down?

My thinking so far is that perhaps there is a method in the UITabBarControllerDelegate?

I haven't seen a SO question on this...

Thanks, this issue has been holding me back hours!


Solution

  • The general idea is, you need to create your own custom UIView, and then pass that into this initialiser.

    let customView = MyCustomBarButtonItem()
    let barButtonItem = UIBarButtonItem(customView: customView)
    

    As for how you implement the custom view so that you can detect touch downs, you have many choices.

    You can either use touchesBegan to detect the touch down, and touchesEnded to detect a "tap" on the bar button item.

    class MyCustomBarButtonItem: UIView {
        // ...
    
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            // ...
        }
    
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            // ...
        }
    }
    

    Another way is to subclass UIButton, and add target/action pairs for the .touchDown/.touchUpInside control events.