ios 向 UIBarButtonItem 添加自定义选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7719237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:49:22  来源:igfitidea点击:

Add a custom selector to a UIBarButtonItem

iphoneobjective-ciosipaduibarbuttonitem

提问by Suchi

I am an iOS newbie. I have a navigation bar button which when clicked should execute a function of my own. What is the best way to do that?

我是iOS新手。我有一个导航栏按钮,单击该按钮时应执行我自己的功能。最好的方法是什么?

UIBarButtonItem *doneBarButtonItem=[[UIBarButtonItem alloc] init];
doneBarButtonItem.title=@"Done";
self.navigationItem.rightBarButtonItem = doneBarButtonItem;
[doneBarButtonItem release];

回答by bryanmac

One way is to init with the target and action:

一种方法是使用目标和操作进行初始化:

UIBarButtonItem *buttonHello = [[UIBarButtonItem alloc] initWithTitle:@"Say Hello"     
    style:UIBarButtonItemStyleBordered target:self action:@selector(sayHello:)];

Another way is to set the target and action after you created it

另一种方法是在创建后设置目标和操作

[buttonHello setTarget:self];
[buttonHello setAction:@selector(sayHello:)];

Target is the instance of the object that will get called. In the case of self, the method will be on this instance of the object.

Target 是将被调用的对象的实例。在 self 的情况下,方法将在对象的这个实例上。

Action is the method that will get called. Typically, you decorate it with IBAction to hint to the designer that it's an action. It compiles to void.

Action 是将被调用的方法。通常,您使用 IBAction 装饰它以提示设计者这是一个动作。它编译为无效。

- (IBAction)sayHello:(id)sender
{
    // code here
}

回答by Luke

There's a variety of different init calls you can use, listed in the Instance Methods section here:

您可以使用各种不同的 init 调用,在此处的实例方法部分中列出:

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIBarButtonItem_Class/Reference/Reference.html

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIBarButtonItem_Class/Reference/Reference.html

- (id)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action
- (id)initWithCustomView:(UIView *)customView
- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action
- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action

Also, you can check out a sample in-use here:

此外,您可以在此处查看正在使用的示例:

How to set target and action for UIBarButtonItem at runtime

如何在运行时为 UIBarButtonItem 设置目标和操作

Hope this helps!

希望这可以帮助!