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.
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];
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With