如何在运行时为UIBarButtonItem设置目标和操作
试过这个,但只适用于UIButton:
[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside]; 
	
 只需直接设置UIBarButtonItem的target和action属性即可。 
我遇到了类似的问题…我假设你的意思是,如果你的UIButton不是你的UITabBar的一部分来调用btnClicked,那么它的工作是适当的。 如果这是您提出的问题,那么请检查您的btnClicked方法并将其更改为:
 -btnClicked:(id)sender 
至
 -(void) btnClicked:(id)sender 
那,并在头文件中声明btnClicked …
对于它的价值,这是我如何设置tabbarbuttonitembutton:
 UIBarButtonItem *exampleButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"button.png"] style:UIBarButtonItemStylePlain target:self action:@selector(btnClicked:)]; 
UIBarButtonItem没有相同的addTarget方法,所以你必须直接设置它们,如下所示
 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); } 
  UIBarButtonItem *barListBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target:self action:@selector(getTruckStopListAction)]; self.navigationItem.rightBarButtonItem = barListBtn; [barListBtn release]; 
 如果您在代码中需要足够的时间,那么继续并扩展我在Swift中完成的UIBarButtonItem是很好的。  🙂 
 import UIKit extension UIBarButtonItem { func addTargetForAction(target: AnyObject, action: Selector) { self.target = target self.action = action } } 
 作为一个例子,作为一个UIViewController ,你只需调用: 
 self.myBarButtonItem.addTargetForAction(self, action: #selector(buttonPressed(_:)) 
如果以编程方式添加UIBarButtonItem,则设置目标和操作的最佳方法是使用以下方法之一初始化该button:
 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)#> 
@ wp42今天工作。
在Objective-C中做这件事的一个很好的方法是向UIBarButtonItem类添加一个类别:
.h文件
 #import <UIKit/UIKit.h> @interface UIBarButtonItem (addons) -(void)addTarget:(id)target andAction:(SEL)action; @end 
.m文件
 #import "UIBarButtonItem+addons.h" @implementation UIBarButtonItem (addons) -(void)addTarget:(id)target andAction:(SEL)action{ [self setTarget:target]; [self setAction:action]; } @end 
在实践中:
 [myBtn addTarget:self andAction:@selector(myFunction:)]; 
 设置你的UIBarButtonItem target和action 
斯威夫特4
 button.target = self button.action = #selector(action) @objc func action (sender:UIButton) { print("action") } 
你可能想尝试addTarget方法。
- 这个行动无法完成。 再试一次(-22421)
 - ios8中的Safari是固定的元素获得焦点时的滚动屏幕
 - 使用自动布局在UICollectionView中指定单元的一个维度
 - Swift 3 URLSession.shared()成员'dataTask的模糊引用(with:completionHandler :) error(bug)
 - 如何在Objective-C中创build一个空白的透明PNG?
 - 将使用相机拍摄的照片捕获并存储到本地数据库/ PhoneGap / Cordova / iOS中
 - 如何防止应用程序运行在电话差距垂直滚动?
 - 什么是NSManagedObjectContext的performBlock:用于?
 - iOS:如何从一个数字中获得一个合适的月份名称?