在Swift中调用目标操作

Jay*_*ske 5 swift

在Swift中,如何使用在运行时确定的选择器执行Cocoa目标操作模式?

手头的细节:我的代码收到一个UIBarButtonItem,它需要调用按钮代表的动作.在Objective-C中,它很简单:

UIBarButtonItem* button = ...;
[button.target performSelector: button.action withObject: self];
Run Code Online (Sandbox Code Playgroud)

在Swift中,performSelector:不会因类型/内存安全原因而暴露.我无法创建一个Swift闭包,因为我在编译时不知道button.action.还有其他任何调用动作的技巧吗?

Jay*_*ske 14

这在Apple开发者论坛中得到了解答:

使用UIApplication.sendAction(_:to:from:forEvent:).从技术上讲,你甚至应该在Objective-C中使用它,因为它理解动作可以采取的各种参数并为你传递它们.

这是我最终使用的代码:

UIApplication.sharedApplication()
    .sendAction(button.action, to: button.target,
                from: self, forEvent: nil)
Run Code Online (Sandbox Code Playgroud)

它与@ vladof的答案具有相同的效果,但它节省了分配UIControl的效果.