1

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!

2 Answers2

4

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 1
    Also you can subclass `UIControl` (or `UIButton`, it doesn't matter) and add `didSet` observer to `isHighlighted`. It is `true` when pressed and `false` otherwise. In addition it handles touching down and moving out out of the box – Tiran Ut Jun 14 '20 at 09:28
0

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")
}
enigma
  • 865
  • 9
  • 22
Wahyudimas
  • 197
  • 6
  • well yes, but this is only _after_ selecting (i.e. after the user lets go..), however I need to animate upon the press down... :) –  Jun 14 '20 at 23:43