How to set an action for an UIBarButtonItem?

11,773

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)))
Share:
11,773

Related videos on Youtube

basti12354
Author by

basti12354

Android Developer and sometimes iOS ;)

Updated on June 05, 2022

Comments

  • basti12354
    basti12354 almost 2 years

    I try to set an action for an UIBarButtonItem like I did before with a normal button:

    1. Select the UIBarButtonItem in storyboard.
    2. Right-Click and pull to my .h-file
    3. Change to action and choose UIBarButtonItem and give the action a name.

          - (IBAction)haupt:(UIBarButtonItem *)sender;
      
    4. 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
    Mike Keskinov over 7 years
    Don't forget the column (:) at the end of method in @selector(myMethod:) !