Tuesday, November 23, 2010

iPhone dev Stupidity 133: switch action for button

UIControl's addTarget:action:forControlEvent: method will allow multiple listeners be added.

If you just care about one listener and want to switch to another action, check this:

@implementation UIButton (Ext)


- (void) switchToAction: (SEL) newSelector forControlEvents: (UIControlEvents) event{

// get the old target/action pair

NSSet * targets = [self allTargets];

assert(targets.count == 1);

id target = [targets anyObject];

NSArray * action_strs = [self actionsForTarget: target forControlEvent: event];

assert(action_strs.count == 1);

NSString * action_name = [action_strs objectAtIndex: 0];

SEL action = NSSelectorFromString(action_name);

// remove it

[self removeTarget: target action: action forControlEvents: event];

// set new selector

[self addTarget: target action: newSelector forControlEvents: event];

}


@end



No comments: