How to set an action for an UIBarButtonItem?
Solution 1
Select the UIBarButton , Create an IBAction by CNRL+Dragging at the implementation section in .m file then try to print with NSLog use breakpoint to know if the control is reaching the IBAction you created.
Solution 2
Here is how you do it with Swift 3:
let check: UIBarButtonItem = UIBarButtonItem()
check.title = "Check"
check.width = CGFloat(100)
check.tintColor = UIColor.green
check.action = #selector(ViewController.checkTapped)
check.target = self
func checkTapped (sender:UIBarButtonItem) {
print("check pressed")
}
Solution 3
myBarButtonItem.target = self;
myBarButtonItem.action = @selector( myMethod: );
Remember action method must have the following signature:
- ( IBAction )myMethod: ( id )sender;
or refer this link : Add a custom selector to a UIBarButtonItem
Solution 4
You need to set an Action:
[self.myButton setAction:@selector(haupt:)];
Or if you are using Storyboard. Right click und pull to you .m file (not .h)
Solution 5
Swift 4:
If you have already create it you can use the customView
property:
barButton.customView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(barButtonTap)))
Related videos on Youtube
Comments
-
basti12354 almost 2 years
I try to set an action for an UIBarButtonItem like I did before with a normal button:
- Select the UIBarButtonItem in storyboard.
- Right-Click and pull to my .h-file
Change to action and choose UIBarButtonItem and give the action a name.
- (IBAction)haupt:(UIBarButtonItem *)sender;
Write some code in the function at my .m-file.
- (IBAction)haupt:(UIBarButtonItem *)sender { NSLog(@"button"); }
Now I try this in the simulator, but nothing happens (No output on the console). What I am doing wrong?
-
Mike Keskinov over 7 yearsDon't forget the column (:) at the end of method in
@selector(myMethod:)
!