简体   繁体   English

UIButton AddTarget多次在同一个目标操作上只调用一次?

[英]UIButton AddTarget multiple times on same target action only calls once?

This is just a quick question, mostly something I've noticed and been rather confused about. 这只是一个简单的问题,大部分是我注意到并且相当困惑的事情。 I've played with addTarget in the past, and noticed that if you're calling addTarget dynamically, and set the same target/action twice on say, a button - using addTarget method. 我过去曾使用过addTarget,并注意到如果你动态调用addTarget,并设置相同的目标/动作两次,比如按钮 - 使用addTarget方法。 Even though we "Added" a target and action more then once, regardless of them being the same target and action, the action itself is only called once. 即使我们“添加”一个目标和动作多一次,无论它们是同一个目标和动作,动作本身只被调用一次。

So, my question - does addTarget ignore adding another target to itself if it already exists in it's stack of target/actions? 所以,我的问题 - 如果addTarget已经存在于其目标/操作堆栈中,那么addTarget是否会忽略向其自身添加另一个目标?

UIButton is a UIControl object, which follows an event-listener pattern, which is often implemented with a hashmap (NSDictionary in Objective-C) of targets (aka Listeners or Observers). UIButton是一个UIControl对象,它遵循一个事件监听器模式,该模式通常使用目标(也称为Listener或Observers)的hashmap(Objective-C中的NSDictionary)实现。 Since a target is added as a key, it is guaranteed not to be added more than once. 由于目标是作为键添加的,因此保证不会添加多次。

The documentation for addTarget:action:forControlEvents: of UIControl describes this behavior as a safety feature: 对于文件addTarget:action:forControlEvents:UIControl描述这种行为作为一种安全功能:

It is also safe to call this method multiple times with the same values for the target and action parameters. 使用相同的目标和操作参数值多次调用此方法也是安全的。 The control maintains a list of its attached targets and actions along [with] the events each supports. 控件维护其附加目标的列表以及每个支持的事件的动作。

To disable response for a given control event, the discussion states that you must remove the target-action registration, which is analogous to removing a key from a hashmap: 要禁用给定控件事件的响应,讨论会指出您必须删除目标操作注册,这类似于从hashmap中删除键:

Specifying a value of 0 for the controlEvents parameter does not prevent events from being sent to a previously registered target and action method. 为controlEvents参数指定值0不会阻止将事件发送到先前注册的目标和操作方法。 To stop the delivery of events, always call the removeTarget:action:forControlEvents: method. 要停止传递事件,请始终调用removeTarget:action:forControlEvents:方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM