我已经给一个UIButton添加了多个目标-动作事件。我想一次性删除所有这些目标-动作事件,而不需要释放任何东西。然后我会设置新的目标。
这是否可能?如何操作?
调用 removeTarget:action:forControlEvents: 方法,将目标(target)参数传递为nil,动作(action)参数传递为NULL,并使用控件掩码(UIControlEventAllEvents)设置所有位。
Objective-C
[someControl removeTarget:nil
action:NULL
forControlEvents:UIControlEventAllEvents];
Swift 2
button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
Swift 3或更高版本
button.removeTarget(nil, action: nil, for: .allEvents)
@progrmr在Swift 2中的回答:
button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
以及Swift 3:
button.removeTarget(nil, action: nil, for: .allEvents)
注意:Swift没有NULL
,因此我尝试将其替换为nil
,似乎可以正常工作。
removeTarget(nil, action: nil, for: .allEvents)
- Sashonil
或NULL
传递给第一个和第二个参数,并且它们都能正常工作。我相信两者都被定义为(void*) 0
(或至少被视为相等)。 - Nicolas MiariSwift 3、4、5:
btnCancel.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
Swift 2:
actionButton.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
Swift 3和4:
actionButton.removeTarget(nil, action: nil, for: .allEvents)
Objective-C:
[actionButton removeTarget: nil action: NULL forControlEvents: UIControlEventAllEvents];
- removeTarget:action:forControlEvents:
这个方法停止将事件传递到指定的目标对象。
Specifying a valid object in the target parameter, this method stops the delivery of the specified events to all action methods associated with that object.
Specifying nil for the target parameter, this method prevents the delivery of those events to all action methods of all target objects
objective-c:
[_myButton removeTarget: //any validObject (or) nil
action:nil
forControlEvents:UIControlEventAllEvents];
swift:
myButton.removeTarget(*validObject or nil*, action:nil, forControlEvents:UIControlEvents.AllEvents)
如果条件允许,您可以更改选择器。 请参见下面的示例
您可以先删除所有目标,然后选择选择器并添加它。
rateButton.removeTarget(nil, action: nil, for: .allEvents)
let action = interview.isRated ? #selector(viewTapped(_:)) : #selector(rateTapped(_:))
rateButton.addTarget(self, action: action, for: .touchUpInside)