user13255207
user13255207

Reputation:

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!

Upvotes: 1

Views: 676

Answers (2)

Wahyudimas
Wahyudimas

Reputation: 217

These are the delegate methods which get called when a user selects a tabBarItem:

// UITabBarDelegate
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    print("Selected item")
}

// UITabBarControllerDelegate
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
    print("Selected view controller")
}

Upvotes: 0

Sweeper
Sweeper

Reputation: 271555

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.

Upvotes: 4

Related Questions