将操作和目标添加到自定义导航BarButtonItem? [英] Adding action and target to a custom Navigation BarButtonItem?

查看:110
本文介绍了将操作和目标添加到自定义导航BarButtonItem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过向rightBarButtonItem添加自定义按钮来自定义导航栏。创建一个非常简单。

I am trying to customize the Navigation Bar by adding a custom button to the rightBarButtonItem. Creating one is pretty straight forward.

UIImage *myImage = [UIImage imageNamed:@"menu-icon.png"];

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setFrame:CGRectMake(0, 0, myImage.size.width, myImage.size.height)];
[myButton setBackgroundImage:myImage forState:UIControlStateNormal];

UIBarButtonItem *myButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myButton];

[navItem setLeftBarButtonItem:myButtonItem animated:YES];

看起来不错,但现在我无法设置目标或动作属性。以下代码不执行任何操作:

Looks good, except that now I can't set the target or action properties. The following code does nothing:

myButtonItem.target = myTarget;
myButtonItem.action = @selector(myButtonAction);

我发现它不起作用的原因是因为我用-initWithCustomView初始化了UIBarButtonItem。苹果文档说:

I found that the reason it's not working is because I initialized the UIBarButtonItem with -initWithCustomView. Apples documentation says:

此方法创建的条形按钮项不会调用其目标的操作方法以响应用户交互。相反,条形按钮项目需要指定的自定义视图处理任何用户交互并提供适当的响应。

我对确切的内容感到有些困惑苹果意味着那个。我应该创建自定义控件还是什么?我还没有真正做到这一点,我不知道从哪里开始。

I'm a little confused by what exactly apple means by that. Am I supposed to create a custom control or something? I haven't really done that yet and I'm not sure where to start.

有没有人对如何做到这一点有任何建议或另一种方法来设置自定义导航栏按钮?

Does anyone have any suggestions on how to do this or an alternative way to set up a custom Navigation Bar Button?

ANSWERED ------------------------- ---------------------------------

只需将此方法添加到UIButton:

Just had to add this method to the UIButton:

[myButton addTarget:myTarget action:@selector(myButtonAction) forControlEvents:UIControlEventTouchUpInside];


推荐答案

这很简单,需要添加目标uibutton不适用于uibarbuttonitem。

It's pretty straight forward, you need to add target for uibutton not for uibarbuttonitem.

要解释更多你想要的uibarbuttonitem是响应内部操作方法,因为文档说你需要为uibutton做这样的事情,因为你是在您的案例uibutton中使用自定义视图初始化您的uibarbuttonitem。

To explain more what you want for uibarbuttonitem is respond touch up inside action method, as documentation says that you need to do that for uibutton as you are initializing your uibarbuttonitem with custom view in your case uibutton.

这篇关于将操作和目标添加到自定义导航BarButtonItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆