我已经为一个UIButton添加了多个target-action-forControlEvents:。我想去除所有这些在一个去不脱销任何东西。然后我会设定新的目标。
这可能吗?我该怎么做?
我已经为一个UIButton添加了多个target-action-forControlEvents:。我想去除所有这些在一个去不脱销任何东西。然后我会设定新的目标。
这可能吗?我该怎么做?
当前回答
- 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:
其他回答
@ program在Swift 2中的回答:
button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
Swift 3:
button.removeTarget(nil, action: nil, for: .allEvents)
注意:Swift没有NULL,所以我测试用nil替换它,它似乎工作得很好。
调用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:
此方法停止将事件传递到指定的目标对象。
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:
Swift 3,4,5:
btnCancel.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
如果选择器是有条件的,则可以更改它。 请看下面的例子
您可以先删除所有目标,然后选择选择器并添加它。
rateButton。removeTarget(nil,动作:nil, for: .allEvents)
let action = interview.isRated ? #selector(viewTapped(_:)) : #selector(rateTapped(_:))
rateButton.addTarget(self, action: action, for: .touchUpInside)