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

标签 ios objective-c cocoa-touch uibutton

这只是一个简单的问题,主要是我注意到但很困惑的问题。我过去玩过 addTarget,并注意到如果您动态调用 addTarget,并在按钮上设置相同的目标/操作两次 - 使用 addTarget 方法。即使我们多次“添加”目标和操作,无论它们是相同的目标和操作,操作本身只被调用一次。

那么,我的问题 - 如果另一个目标已经存在于它的目标/操作堆栈中,addTarget 是否会忽略向自身添加另一个目标?

最佳答案

UIButton 是一个 UIControl 对象,它遵循事件监听器模式,通常使用目标(也称为监听器)的 HashMap (Objective-C 中的 NSDictionary)来实现或观察员)。由于将目标添加为键,因此保证不会添加多次。

UIControladdTarget: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/

相关文章:

objective-c - 制作类成员属性并合成它们

objective-c - 表格 View 的最后四行不会从键盘下方移出

ios - 将 Google+ 集成到 iOS 应用程序中

iphone - 如何停止来自另一个类/ View 的位置更新?

ios - 从已知值创建 CNPostalAddress

ios - 带有 iCloud 的 CoreData 驱动应用程序中带有 NSSortDescriptor 和 NSFetchedResultsController 的自定义部分

ios - 图像未在 ipad 模拟器中显示

swift - 将 50 的 layer.cornerRadius 应用于按钮时出现奇怪的结果

ios - 如何为 iOS 存折创建 "generic type pass"?

ios - 使用 Twitter 框架自动从 iOS 应用程序发送推文 - 不使用 TWTweetComposeViewController