Thursday 29 January 2015

Programmatically trigger UIButton action . Calling Method from button @selector.

- (void)sendActionsForControlEvents:(UIControlEvents)controlEvents

Parameters:  controlEvents 
A bitmask whose set flags specify the control events for which action messages are sent. See Control Events for bitmask constants.
Description:Sends action messages for the given control events.UIControl implements this method to send all action messages associated with controlEvents, 
repeatedly invoking sendAction:to:forEvent: in the process. 
The list of targets and actions it looks up is constructed from prior invocations of addTarget:action:forControlEvents:.


Eg:
To call a method  MySecretMethod in newViewController 
[newViewController.button  addTarget: self 
                                              action@selector (MySecretMethod)  
                                              forControlEvents:  UIControlEventTouchUpInside];


Method 1: declare MySecretMethod in .h of newViewController and call it
 by its object (so it wont be secret as can be accessed from anywhere.)
                 [newViewController MySecretMethod];

Method 2: declare button in .h of newViewController and call button action using following statement
[newViewController.button sendActionsForControlEventsUIControlEventTouchUpInside];


Looping SuperView 
You can add or change the button action by looping superview view using addTarget:action:forControlEvents:
for(UIButton *aButton in self.view.subviews){
        if([aButton isKindOfClass:[UIButton class]]){
            [aButton addTarget: self 
                     action:@selector(buttonClick:) 
                     forControlEvents: UIControlEventTouchUpInside];
             }
    }


Read More: