Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke target action in Swift

Tags:

swift

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?

like image 327
Jay Lieske Avatar asked Jul 07 '14 00:07

Jay Lieske


1 Answers

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.

like image 96
Jay Lieske Avatar answered Oct 07 '22 06:10

Jay Lieske