Search code examples
iosswiftuibuttonuibarbuttonitemuitabbar

How to fire a UIBarButtonItem tap event manually?


I have a situation where I have a custom UIButton that is a subview of a UIBarButtonItem:

guard let tab1 = self.tabBar.items![0].value(forKey: "view") as? UIView else {return}

    let button2Test = UIButton()
    tab1.addSubview(button2Test)

The custom UIButton, has a target:

button2Test.addTarget(self, action: #selector(buttonTouchUpInsideP3), for: [.touchUpInside])
button2Test.addTarget(self, action: #selector(buttonTouchInsideBoundsP3), for: [.touchDown, .touchDragEnter])
button2Test.addTarget(self, action: #selector(buttonDraggedOutOfBoundsP3), for: [.touchDragExit, .touchCancel])

Basically, in the buttonTouchUpInsideP3 function, I want to programmatically / manually make the UIBarButtonItem at a specific index to fire as if it was tapped on, since the target of the UIButton does not allow the actual UIBarButtonItem underneath to be tapped, unfortunately...

My attempt which did not work because of errors is: (which I got from an outdated Q). Note that I call this in the buttonTouchUpInsideP3 target function which ones once you've let go of the button.

let homeTabBarItem = self.tabBar.items![0]
UIApplication.sharedApplication.sendAction(homeTabBarItem.action, to: homeTabBarItem.target, from: nil, forEvent: nil)

Solution

  • I figured out how to do it:

    tabBarController.selectedIndex = 0
    

    Just put this in the buttonTouchUpInside function! ;)

    You should probably also call:

    self.tabBar(self.tabBar, didSelect: self.tabBar.items![0])