【问题标题】:Press UIBarButtonItem programmatically in swift?以编程方式快速按下 UIBarButtonItem?
【发布时间】:2015-07-16 19:36:21
【问题描述】:

我有一个栏按钮项目,我想以编程方式按下,基本上相当于

buttonObj.sendActionsForControlEvents(UIControlEvents.TouchUpInside)

但作为条形按钮项

编辑:我忘了提,我不能简单地调用按钮的操作方法,因为我使用的是 SWRevealViewController 库并在栏按钮项目上使用他们的"revealToggle:" 操作,我不确定如何自行调用。

【问题讨论】:

  • 也许performSelector 可以帮忙?
  • @Aladin 在 Swift 中,performSelector: 由于内存原因不存在

标签: ios swift cocoa-touch uikit uibarbuttonitem


【解决方案1】:

如果您查看 Objective-C 等效问题,您会看到使用 performSelector: 的实现。在 Swift 中,您无权访问此方法。这是来自 Apple 的官方说法:

performSelector: 方法和相关的选择器调用方法在 Swift 中没有被导入,因为它们本质上是不安全的。

您可以改用UIApplication.sendAction(_:to:from:forEvent:) 来解决此问题。从技术上讲,您也应该在 Objective-C 中这样做。

假设您的UIBarButtonItem 定义为barButtonItem。以下代码可以满足您的要求。

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

【讨论】:

  • 这很棒。谢谢!!
【解决方案2】:

Swift 4(和 3)语法

UIApplication.shared.sendAction(barButtonItem.action!, to: barButtonItem.target, from: self, for: nil)

【讨论】:

    【解决方案3】:

    适用于 Swift 5

    _ = button.target?.perform(button.action, with: nil)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      相关资源
      最近更新 更多