我已经为一个UIButton添加了多个target-action-forControlEvents:。我想去除所有这些在一个去不脱销任何东西。然后我会设定新的目标。

这可能吗?我该怎么做?


当前回答

调用removeTarget:action:forControlEvents:,为目标传递nil,为动作传递NULL,并使用一个设置所有位的控制掩码(UIControlEventAllEvents)。

objective - c

[someControl removeTarget:nil 
                   action:NULL 
         forControlEvents:UIControlEventAllEvents];

斯威夫特2

button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)

Swift 3或更高

button.removeTarget(nil, action: nil, for: .allEvents)

其他回答

调用removeTarget:action:forControlEvents:,为目标传递nil,为动作传递NULL,并使用一个设置所有位的控制掩码(UIControlEventAllEvents)。

objective - c

[someControl removeTarget:nil 
                   action:NULL 
         forControlEvents:UIControlEventAllEvents];

斯威夫特2

button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)

Swift 3或更高

button.removeTarget(nil, action: nil, for: .allEvents)

@ program在Swift 2中的回答:

button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)

Swift 3:

button.removeTarget(nil, action: nil, for: .allEvents)

注意:Swift没有NULL,所以我测试用nil替换它,它似乎工作得很好。

Swift 3,4,5:

btnCancel.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)

斯威夫特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)

详情https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIControl_Class/index.html#//apple_ref/occ/instm/UIControl/removeTarget:action:forControlEvents: