Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set target and action for UIBarButtonItem at runtime

Tried this but only works for UIButton:

[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
like image 226
Sharief Avatar asked Feb 25 '10 11:02

Sharief


3 Answers

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

like image 188
Ole Begemann Avatar answered Sep 26 '22 00:09

Ole Begemann


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);
}
like image 29
mihai Avatar answered Sep 26 '22 00:09

mihai


Set target and action of your UIBarButtonItem

Swift 5 & 4

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

@objc func action (sender:UIButton) {
    print("action")
}
like image 40
Haroldo Gondim Avatar answered Sep 22 '22 00:09

Haroldo Gondim