How to set target and action for UIBarButtonItem a

2019-01-23 00:36发布

Tried this but only works for UIButton:

[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];

9条回答
叼着烟拽天下
2楼-- · 2019-01-23 00:52
  UIBarButtonItem *barListBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target:self action:@selector(getTruckStopListAction)];   
    self.navigationItem.rightBarButtonItem = barListBtn;
    [barListBtn release];
查看更多
Evening l夕情丶
3楼-- · 2019-01-23 00:56

I ran into a similar problem... I assume you mean that if your UIButton is not part of your UITabBar to call btnClicked then it works appropriately. If this is the problem you are proposing then, check your btnClicked method and change it from:

-btnClicked:(id)sender

to

-(void) btnClicked:(id)sender

that, and declare btnClicked in the header file...

For what it's worth, this is how I setup a button in tabbarbuttonitem:

UIBarButtonItem *exampleButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"button.png"] style:UIBarButtonItemStylePlain target:self action:@selector(btnClicked:)];
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-23 00:57

Set target and action of your UIBarButtonItem

Swift 4

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

@objc func action (sender:UIButton) {
    print("action")
}
查看更多
三岁会撩人
5楼-- · 2019-01-23 01:03

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

查看更多
forever°为你锁心
6楼-- · 2019-01-23 01:05

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(_:))
查看更多
女痞
7楼-- · 2019-01-23 01:06

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)#>
查看更多
登录 后发表回答