Tried this but only works for UIButton:
[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
@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:)];
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.
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)#>
UIBarButtonItem *barListBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target:self action:@selector(getTruckStopListAction)];
self.navigationItem.rightBarButtonItem = barListBtn;
[barListBtn release];
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(_:))