Reputation: 2646
I have a bar button item that I want to press programmatically, basically the equivalent of
buttonObj.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
but as a bar button item
edit: I forgot to mention, I can't simply call the action method for the button since I'm using the SWRevealViewController library and using their "revealToggle:"
action on the bar button item, which I'm not sure how to call on its own.
Upvotes: 8
Views: 6590
Reputation: 4565
Works in Swift 5:
_ = button.target?.perform(button.action, with: nil)
Upvotes: 6
Reputation: 136
Swift 4 (and 3) syntax
UIApplication.shared.sendAction(barButtonItem.action!, to: barButtonItem.target, from: self, for: nil)
Upvotes: 8
Reputation:
If you look at Objective-C equivalent questions, you'll see implementations that use performSelector:
. In Swift, you don't have access to this method. Here's the official word on it from Apple:
The performSelector: method and related selector-invoking methods are not imported in Swift because they are inherently unsafe.
You can solve this problem by using UIApplication.sendAction(_:to:from:forEvent:)
instead. Technically, you should be doing this in Objective-C too.
Let's say your UIBarButtonItem
is defined as barButtonItem
. The following code would do what you are asking.
UIApplication.sharedApplication().sendAction(barButtonItem.action, to: barButtonItem.target, from: self, forEvent: nil)
Upvotes: 16