How to set target and action for UIBarButtonItem at runtime

IosObjective CIphoneSwiftUibarbuttonitem

Ios Problem Overview


Tried this but only works for UIButton:

[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];

Ios Solutions


Solution 1 - Ios

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

Solution 2 - Ios

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 - Ios

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 - Ios

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 - Ios

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(_:))

Solution 6 - Ios

UIBarButtonItem *barListBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target:self action:@selector(getTruckStopListAction)];   
self.navigationItem.rightBarButtonItem = barListBtn;
[barListBtn release];

Solution 7 - Ios

@wp42 It does work today.

A nifty way of doing this in objective-C is adding a category to UIBarButtonItem class:

.h file

#import <UIKit/UIKit.h>

@interface UIBarButtonItem (addons)

-(void)addTarget:(id)target andAction:(SEL)action;

@end

.m file

#import "UIBarButtonItem+addons.h"

@implementation UIBarButtonItem (addons)

-(void)addTarget:(id)target andAction:(SEL)action{
   [self setTarget:target];
   [self setAction:action];
}

@end

In practice:

[myBtn addTarget:self andAction:@selector(myFunction:)];

Solution 8 - Ios

For custom views: use an UITapGestureRecognizer and set up isUserInteractionEnabled to true.

profileImageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(handleProfileImageTap))
profileImageView.addGestureRecognizer(tap)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: profileImageView)

Solution 9 - Ios

If you are programmatically adding the UIBarButtonItem, the best way to set the target and action is to initialize the button with one of the following methods:

UIBarButtonItem *customButton = [[UIBarButtonItem alloc] initWithImage:<#(UIImage)#> style:<#(UIBarButtonItemStyle)#> target:<#(id)#> action:<#(SEL)#>

UIBarButtonItem *customButton = [UIBarButtonItem alloc] initWithTitle:<#(NSString *)#> style:<#(UIBarButtonItemStyle)#> target:<#(id)#> action:<#(SEL)#>

UIBarButtonItem *customButton = [UIBarButtonItem alloc] initWithImage:<#(UIImage *)#> landscapeImagePhone:<#(UIImage *)#> style:<#(UIBarButtonItemStyle)#> target:<#(id)#> action:<#(SEL)#>

Solution 10 - Ios

Swift 5:

Extract to extensions:

extension UIBarButtonItem {
    
    static func nextBtn(target: AnyObject, action: Selector) -> UIBarButtonItem {
        let title = "Next"
        return button(title: title, target: target, action: action)
    }
    
    private static func button(title: String, target: AnyObject, action: Selector) -> UIBarButtonItem {
        return UIBarButtonItem(title: title, style: .done, target: target, action: action)
    }
    
}

Call in code:

navigationItem.rightBarButtonItem = .nextBtn(target: self, action: #selector(rightBarButtonAction))

Action:

@objc func rightBarButtonAction() {
    Swift.print("Button tapped!")
}

Pretty easy to add new buttons to this factory.

Solution 11 - Ios

You may want to try out the addTarget method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShariefView Question on Stackoverflow
Solution 1 - IosOle BegemannView Answer on Stackoverflow
Solution 2 - IosmihaiView Answer on Stackoverflow
Solution 3 - IosHaroldo GondimView Answer on Stackoverflow
Solution 4 - IosJ. DaveView Answer on Stackoverflow
Solution 5 - IosserennView Answer on Stackoverflow
Solution 6 - Iossinh99View Answer on Stackoverflow
Solution 7 - IosItai SpectorView Answer on Stackoverflow
Solution 8 - IososkarkoView Answer on Stackoverflow
Solution 9 - IosAdam CooperView Answer on Stackoverflow
Solution 10 - IosatereshkovView Answer on Stackoverflow
Solution 11 - IosDavid CarvalhoView Answer on Stackoverflow