How to get UIButton Target, Action and Control events?

后端 未结 3 1034
时光取名叫无心
时光取名叫无心 2020-12-08 23:02

I am using UIImageView\'s with UIButtons a whole bunch. So, I created a custom class to permanently marry these two an make things a little simpler. It all works well unti

相关标签:
3条回答
  • 2020-12-08 23:04

    Showing how to iterate over a button's targets and create copies of the selector on another button. Specific example is just the touchupinside event, but that's usually all I use.

    for (id target in button.allTargets) {
         NSArray *actions = [button actionsForTarget:target
                                          forControlEvent:UIControlEventTouchUpInside];
         for (NSString *action in actions) {
              [newButton addTarget:target action:NSSelectorFromString(action) forControlEvents:UIControlEventTouchUpInside];
         }
    }
    
    0 讨论(0)
  • 2020-12-08 23:12

    I used this to remove any possible unwanted target/action before assigning a new one:

    if let action = button.actions(forTarget: target, forControlEvent: .touchUpInside)?.first
    {
        button.removeTarget(target, action: NSSelectorFromString(action), for: .touchUpInside)
    }
    

    or if you really want to remove all actions:

    if let actions = button.actions(forTarget: target, forControlEvent: .touchUpInside)
    {
        for action in actions
        {
            button.removeTarget(target, action: NSSelectorFromString(action), for: .touchUpInside)
        }
    }
    
    0 讨论(0)
  • 2020-12-08 23:27

    UIControl's allTargets and allControlEvents are the way to start. The final piece of the puzzle is actionsForTarget:forControlEvent:, call it once for each target and event.

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