且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Swift中,如何检测哪个UIControlEvents触发了该动作?

更新时间:2023-02-13 20:41:13

不幸的是,您无法区分是哪个控制事件触发了动作处理程序.这与Swift无关.这只是可可的功能.

Unfortunately, you cannot distinguish what control event triggered an action handler. This has nothing to do with Swift; it's just a feature of Cocoa.

这是一个奇怪的设计决定,但事实就是如此.参见例如我的书,它对此抱怨:

It's a strange design decision, but that's just how it is. See, for example, my book, which complains about it:

奇怪的是,没有一个动作选择器参数提供任何方法来了解哪个控制事件触发了当前的动作选择器调用!因此,例如,要将内部向上触摸"控制事件与外部向上触摸"控制事件区分开,它们对应的目标-操作对必须指定两个不同的操作处理程序;如果将它们分派到同一操作处理程序,则该处理程序将无法发现发生了哪个控制事件.

Curiously, none of the action selector parameters provide any way to learn which control event triggered the current action selector call! Thus, for example, to distinguish a Touch Up Inside control event from a Touch Up Outside control event, their corresponding target–action pairs must specify two different action handlers; if you dispatch them to the same action handler, that handler cannot discover which control event occurred.