这只是一个简单的问题,主要是我注意到但很困惑的问题。我过去玩过 addTarget,并注意到如果您动态调用 addTarget,并在按钮上设置相同的目标/操作两次 - 使用 addTarget 方法。即使我们多次“添加”目标和操作,无论它们是相同的目标和操作,操作本身只被调用一次。
那么,我的问题 - 如果另一个目标已经存在于它的目标/操作堆栈中,addTarget 是否会忽略向自身添加另一个目标?
最佳答案
UIButton
是一个 UIControl
对象,它遵循事件监听器模式,通常使用目标(也称为监听器)的 HashMap (Objective-C 中的 NSDictionary)来实现或观察员)。由于将目标添加为键,因此保证不会添加多次。
UIControl
的addTarget:action:forControlEvents:
文档将此行为描述为一项安全功能:
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.
要禁用给定控制事件的响应,讨论指出您必须删除目标操作注册,这类似于从 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. To stop the delivery of events, always call the removeTarget:action:forControlEvents: method.
关于ios - UIButton AddTarget 在同一目标操作上多次只调用一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24845469/