13

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?

basti12354
  • 2,490
  • 4
  • 24
  • 43

7 Answers7

7

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.

codeIgnitor
  • 765
  • 1
  • 5
  • 16
6

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")
}
Robert Smith
  • 634
  • 1
  • 8
  • 22
Ondrej Kvasnovsky
  • 4,592
  • 3
  • 30
  • 40
5
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

Community
  • 1
  • 1
Himanshu padia
  • 7,428
  • 1
  • 47
  • 45
2

Swift 4:

If you have already create it you can use the customView property:

barButton.customView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(barButtonTap)))
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
1

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)

alex
  • 8,904
  • 6
  • 49
  • 75
1

You can use belowed code it is working

    UIBarButtonItem *barButton=[[UIBarButtonItem alloc]init];
    barButton.title=@"Back";
    [barButton setTarget:self];
    [barButton setAction:@selector(uiBarBurronAction:)];

Button Action

-(IBAction)uiBarBurronAction:(id)sender
{
        NSLog(@"barbutton Pressed")

} 

Otherwise you can set selector RightClick on uibarbuttonitem and drag selector and give action to viewcontroller

Kalpit Gajera
  • 2,475
  • 1
  • 14
  • 24
0

You ctrl-drag the button to you header file and create an IBOutlet.

Then you wire the button with the IBAction, all good.