如何使用代码在 Swift iOS8 中模拟按钮按下

Posted

技术标签:

【中文标题】如何使用代码在 Swift iOS8 中模拟按钮按下【英文标题】:How can I simulate a button press in Swift iOS8 using code 【发布时间】:2015-02-09 08:36:49 【问题描述】:

如何在使用 Swift 的视图中模拟按钮按下。我正在尝试获取日历权限并设置功能以在单击当前运行的开始按钮时检查此授权

@IBAction func start(sender: AnyObject) 
//loads prompt to "Allow" or "Don't Allow" calendar permissions
eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: handler)

//checkAuth function looks at calendar authorization to get current status 
and then acts accordingly to dismiss View or load Privacy Settings
checkAuth()


我需要能够模拟按下开始按钮以再次触发 start() 函数。到目前为止,我发现的唯一东西似乎是在 Objective-C 中

[buttonObj sendActionsForControlEvents: UIControlEventTouchUpInside];

我不熟悉 Obj-C,如果可能的话,我需要一种在 Swift 中实现它的方法...谢谢

【问题讨论】:

【参考方案1】:

以下的 Swift 翻译:

[buttonObj sendActionsForControlEvents: UIControlEventTouchUpInside];

是:

button.sendActions(for: .touchUpInside)

它实际上应该模拟按钮按下。

【讨论】:

【参考方案2】:

尝试调用您的 IBAction 函数:

self.start(self)

【讨论】:

【参考方案3】:

斯威夫特 3

button.sendActions(for: UIControlEvents.touchUpInside)

斯威夫特 4

button.sendActions(for: .touchUpInside)

【讨论】:

以上是关于如何使用代码在 Swift iOS8 中模拟按钮按下的主要内容,如果未能解决你的问题,请参考以下文章