How to set target and action for UIBarButtonItem at runtime

93,214

Solution 1

Just set the UIBarButtonItem's target and action properties directly.

Solution 2

UIBarButtonItem doesnt have the same addTarget method so you have to set them directly as follows

btn.target = self;
btn.action = @selector(barButtonCustomPressed:);

...

// can specify UIBarButtonItem instead of id for this case
-(IBAction)barButtonCustomPressed:(UIBarButtonItem*)btn 
{
    NSLog(@"button tapped %@", btn.title);
}

Solution 3

Set target and action of your UIBarButtonItem

Swift 5 & 4

button.target = self
button.action = #selector(action)

@objc func action (sender:UIButton) {
    print("action")
}

Solution 4

I ran into a similar problem... I assume you mean that if your UIButton is not part of your UITabBar to call btnClicked then it works appropriately. If this is the problem you are proposing then, check your btnClicked method and change it from:

-btnClicked:(id)sender

to

-(void) btnClicked:(id)sender

that, and declare btnClicked in the header file...

For what it's worth, this is how I setup a button in tabbarbuttonitem:

UIBarButtonItem *exampleButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"button.png"] style:UIBarButtonItemStylePlain target:self action:@selector(btnClicked:)];

Solution 5

If you need this enough times in your code, it's nice to go ahead and extend UIBarButtonItem which I've done below in Swift. :)

import UIKit

extension UIBarButtonItem {
    func addTargetForAction(target: AnyObject, action: Selector) {
        self.target = target
        self.action = action
    }
}

As an example, with self as a UIViewController, you'd simply call:

self.myBarButtonItem.addTargetForAction(self, action: #selector(buttonPressed(_:))
Share:
93,214
Sharief
Author by

Sharief

Summary: Over 15 years of technical experience in the field of Software Engineering. Twelve years as a Technical Project Lead and Senior Software Engineer. Practitioner of the Agile Methodology to promote adaptive and iterative development. Certified ScrumMaster® (CSM) from the Scrum Alliance International experience in leading technical teams overseas. Works well in both team environments and individual assignments. Excellent communications skills, dedicated and hardworking individual. Effective contributor at all levels of the organization. Master of Science (M.S.) in Computer Science from Johns Hopkins University. Bachelor of Science (B.S.) in Electrical Engineering from University of Maryland College Park. In Progress: • Project Management Professional (PMP) Certification from PMI

Updated on July 05, 2022

Comments

  • Sharief
    Sharief almost 2 years

    Tried this but only works for UIButton:

    [btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
  • J. Dave
    J. Dave about 14 years
    additionally, you can take out the ":" making ...:@selector(btnClicked:)]; into ...:@selector(btnClicked)];
  • Shaggy Frog
    Shaggy Frog over 13 years
    N.B. This only works if the UIBarButtonItem doesn't use a custom view, like a UIButton
  • Jarrod
    Jarrod over 11 years
    For custom views, use: [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
  • Mike
    Mike over 10 years
    There is no addTarget method for UIBarButtonItem.
  • katzenhut
    katzenhut over 10 years
    That methohd does not exist, check the docs please: developer.apple.com/library/IOs/documentation/UIKit/Referenc‌​e/… What you are thinking of is a UIButton
  • Eichhörnchen
    Eichhörnchen over 9 years
    Thank you!! this is exactly what i needed to implement my custom UIBarButtonItem class
  • mikebz
    mikebz over 9 years
    great answer, especially if you want to create the buttons at design time!
  • Unome
    Unome about 9 years
    Can you please give an example of what those should be set to? The target says it takes an AnyObject? Should that be set to a UIGestureRecognizer?
  • zmonteca
    zmonteca about 9 years
    assuming btn is a UIBarButtonItem, [btn setTarget:self]; [btn setAction:@selector(btnClicked:)] or DOT notation btn.target = self; btn.action = @selector(btnClicked:); Both should work as @Ole-Begemann is describing.
  • Admin
    Admin almost 8 years
    @zmonteca hey, does it still work (6 years later)? how can I set a target and action to a UITabBarItem today?
  • zmonteca
    zmonteca almost 8 years
    @wp42 Should still work. This was just used last year on my end.
  • matt.writes.code
    matt.writes.code over 7 years
    Per the documentation this doesn't work on an instance that has been initialized with a custom view. "The bar button item created by this method does not call the action method of its target in response to user interactions. Instead, the bar button item expects the specified custom view to handle any user interactions and provide an appropriate response." See apple.co/2egXdmR for reference
  • Yodagama
    Yodagama almost 4 years
    This only works if the UIBarButtonItem doesn't use a custom view.
  • Yodagama
    Yodagama almost 4 years
    This only works if the UIBarButtonItem doesn't use a custom view
  • Ximena Flores de la Tijera
    Ximena Flores de la Tijera over 2 years
    Did you figure out what worked if you used a custom view?