如何在UIBarButton上点击事件

时间:2016-02-15 06:52:12

标签: ios swift uibarbuttonitem uicontrol uicontrolevents

由于UIBarButton未从UIResponder/UIControl继承,UIBarButton上的点击事件如何运作?

2 个答案:

答案 0 :(得分:3)

  

直接创建UIBarButtonItem的targetaction属性。

UIBarButtonItem *barListBtn = [[UIBarButtonItem alloc] initWithTitle:@"yourTitle" 
                             style:UIBarButtonItemStylePlain 
                            target:self action:@selector(btnClicked:)];   
self.navigationItem.rightBarButtonItem = barListBtn;



-(void)btnClicked:(UIBarButtonItem*)btn 
{
NSLog(@"button tapped %@", btn.title);
}

<强>选择-2

- (void) viewDidLoad
{
[super viewDidLoad];

// first we create a button and set it's properties
UIBarButtonItem *myButton = [[UIBarButtonItem alloc]init];
myButton.action = @selector(doTheThing);
myButton.title = @"Hello";
myButton.target = self;

// then we add the button to the navigation bar
self.navigationItem.rightBarButtonItem = myButton;


}


// method called via selector
- (void) doTheThing {

NSLog(@"Doing the thing");

}

一些额外的Sample

答案 1 :(得分:0)

UIBarItem是一个抽象超类,用于添加到屏幕底部显示的栏中的项目。条形图上的项目的行为类似于按钮(UIButton的实例)。 他们有标题,图片,操作和目标。您还可以在栏上启用和禁用项目。

有关详细信息,请查看以下链接: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIBarItem_Class/index.html#//apple_ref/occ/cl/UIBarItem

<强>夫特:  在viewDidLoad

中添加以下行
self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:"), animated: true)

功能:

 func barButtonItemClicked()
    {
       print("Bar button clicked") 
    }