在 Swift 中,如何使用运行时确定的选择器执行 Cocoa 目标- Action 模式?
手头的细节:
我的代码收到一个 UIBarButtonItem
,它需要调用按钮代表的操作。在 Objective-C 中,它很简单:
UIBarButtonItem* button = ...;
[button.target performSelector: button.action withObject: self];
在 Swift 中,performSelector:
出于类型/内存安全原因未公开。我无法创建 Swift 闭包,因为我在编译时不知道 button.action。调用该操作的任何其他技术?
最佳答案
这在 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.
这是我最终使用的代码:
UIApplication.sharedApplication()
.sendAction(button.action, to: button.target,
from: self, forEvent: nil)
它与@vladof 的答案具有相同的效果,但它节省了分配 UIControl。
关于swift - 在 Swift 中调用目标操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24601765/