在Swift中以编程方式按下UIBarButtonItem?

8
我有一个条形按钮项目,我想以编程方式按下它,基本上相当于
buttonObj.sendActionsForControlEvents(UIControlEvents.TouchUpInside)

但是作为一个栏按钮项

编辑:我忘了提到,我不能简单地调用按钮的操作方法,因为我正在使用SWRevealViewController库,并在栏按钮项上使用它们的“revealToggle:”操作,我不知道如何自己调用。


也许 performSelector 可以帮忙? - Alaeddine
1
在Swift中,performSelector:由于内存原因不可用。 - user3857868
3个回答

16

如果你看一下关于Objective-C等价问题的答案,你会看到使用performSelector:方法的实现。在Swift中,你无法访问这个方法。以下是苹果官方对此的解释:

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

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

假设你的UIBarButtonItem被定义为barButtonItem。下面的代码将实现你要求的功能。

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

这太棒了。谢谢!! - Cole

8

Swift 4 (和3) 语法

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

6

Swift 5中可用的内容:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接