In Swift, how do I execute the Cocoa target-action pattern with a selector determined at runtime?
The specifics at hand:
My code receives a UIBarButtonItem
, and it needs invoke the action that button represents. In Objective-C, it's straightforward:
UIBarButtonItem* button = ...;
[button.target performSelector: button.action withObject: self];
In Swift, performSelector:
is not exposed for type/memory safety reasons. I can't create a Swift closure since I don't know the button.action at compile time. Any other technique for invoking the action?
This was answered in the Apple Developer Forums:
Use
UIApplication.sendAction(_:to:from:forEvent:)
. Technically, you should be using that even in Objective-C, because it understands the various kinds of parameters an action can take and passes them for you.
Here's the code I ended up using:
UIApplication.sharedApplication()
.sendAction(button.action, to: button.target,
from: self, forEvent: nil)
It has the same effect as @vladof's answer, but it saves allocating the UIControl.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With