将自定义选择器添加到UIBarButtonItem

将自定义选择器添加到UIBarButtonItem

本文介绍了将自定义选择器添加到UIBarButtonItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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


推荐答案

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

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是将被调用的对象的实例。在self的情况下,该方法将在该对象的实例上。

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.

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

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.

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

这篇关于将自定义选择器添加到UIBarButtonItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 16:06