【问题标题】:Invoke target action in Swift在 Swift 中调用目标动作
【发布时间】:2014-07-07 00:57:55
【问题描述】:

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

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

UIBarButtonItem* button = ...;
[button.target performSelector: button.action withObject: self];

在 Swift 中,出于类型/内存安全原因,performSelector: 未公开。我无法创建 Swift 闭包,因为我在编译时不知道 button.action。是否有任何其他技术可以调用该操作?

【问题讨论】:

    标签: swift


    【解决方案1】:

    这已在Apple Developer Forums

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

    这是我最终使用的代码:

    UIApplication.sharedApplication()
        .sendAction(button.action, to: button.target,
                    from: self, forEvent: nil)
    

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

    【讨论】:

      【解决方案2】:

      假设 Objective C 类 TestClass 中有一个方法返回一个 UIBarButtonItem:

      - (UIBarButtonItem *)getBarButtonItem
      {
          UIBarButtonItem *bar = [[UIBarButtonItem alloc] init];
          bar.target = self;
          bar.action = @selector(help);
          return bar;
      }
      
      - (void)help
      {
          NSLog(@"Help offered");
      }
      

      在斯威夫特中:

      var testClass = TestClass()
      var barButtonItem = testClass.getBarButtonItem()
      var button: UIButton = UIButton()
      button.sendAction(barButtonItem.action, to: barButtonItem.target, forEvent: nil)
      

      控制台日志:

      2014-07-06 23:49:49.942 TestApp [53986:2552835] 提供帮助

      还要注意,我们可以实例化 UIControl 而不是 UIButton。

      【讨论】:

      • 替代方案:(只是为了保持帖子同步)还有另一种方法可以使用NSThread.detachNewThreadSelector 对目标调用操作,请参考this question
      猜你喜欢
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      相关资源
      最近更新 更多