UIButton remove all target-actions

后端 未结 5 926
广开言路
广开言路 2020-12-04 05:02

I have added multiple target-action-forControlEvents: to a UIButton. I\'d like to remove all of these in one go without deallocating anything. I will then set new targets.

相关标签:
5条回答
  • 2020-12-04 05:09

    Call removeTarget:action:forControlEvents:, pass nil for the target, NULL for action, and use a control mask that sets all bits (UIControlEventAllEvents).

    Objective-C

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

    Swift 2

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

    Swift 3 or higher

    button.removeTarget(nil, action: nil, for: .allEvents)
    
    0 讨论(0)
  • 2020-12-04 05:10
    - removeTarget:action:forControlEvents:
    

    This method stops the delivery of events to the specified target object.

    1. 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.

    2. 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)
      

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

    0 讨论(0)
  • 2020-12-04 05:20

    Swift:

    btnCancel.removeTarget(self, action: Selector(), forControlEvents: UIControlEvents.AllEvents)
    
    0 讨论(0)
  • 2020-12-04 05:28

    @progrmr's answer in Swift 2:

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

    and Swift 3:

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

    Note: Swift doesn't have NULL, so I tested replacing it with nil and it seems to work fine.

    0 讨论(0)
  • 2020-12-04 05:33

    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];
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题