swift - 在 Swift 中调用目标操作

标签 swift

在 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/

相关文章:

ios - 自动调整大小的 tableView 高度错误

ios - 从我的应用程序内部控制其他应用程序的音乐播放?

ios - display_timer_callback : unexpected state when scroll

ios - UITabBar事件处理

ios - 在一个属性字符串中使用多种样式

Swift UITableViewCell subview 不注册点击

ios - 使用 Swift 比较类型

ios - 如何在不让 UIView 移动到角落的情况下使用大小约束?

operator-overloading - 还不支持运算符重载?

swift - 是否可以将用户位置从 iOS 应用程序发送到网络服务器?