Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Action Listener Programmatically in IOS

Hi I have created a button programmatically. I will add this button to the navigation bar. Now I want to add a Touch Up Inside action listener to it. How do I do it? Thanks.

like image 977
Tahlil Avatar asked Dec 02 '12 11:12

Tahlil


2 Answers

A UIButton is a subclass of UIControl.

All you need to do after creating an button is to set the target and action of the button. i.e.

// Create your button:
UIButton *button = // However you create your button

// Set the target, action and event for the button
[button addTarget:// the object that implements the action method, or nil if you want it to propagate up the responder chain.
           action:// A selector for the method
 forControlEvents:UIControlEventTouchUpInside];
like image 169
Abizern Avatar answered Oct 14 '22 11:10

Abizern


Since you've added them to a navigation bar, it's slightly different, but basically the same. You will add the listener/handler at the same time you create the button(s). Here I've added << and >> to a navigation bar using the following:

UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithTitle:@">>" style:UIBarButtonItemStylePlain target:self action:@selector(navNextButtonPressed)];
UIBarButtonItem *prevButton = [[UIBarButtonItem alloc] initWithTitle:@"<<" style:UIBarButtonItemStylePlain target:self action:@selector(navPrevButtonPressed)];
self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:nextButton, prevButton, nil];

and then create your handlers as normal:

#pragma mark - button handling
-(void)navNextButtonPressed
{    
    NSLog(@"Next pressed");
}

-(void)navPrevButtonPressed
{
    NSLog(@"Prev pressed");
}
like image 35
Madivad Avatar answered Oct 14 '22 09:10

Madivad