将操作和目标添加到自定义导航BarButtonItem?

时间:2013-07-31 19:38:39

标签: ios ios6 uibarbuttonitem

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

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];

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

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

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

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

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

有没有人对如何设置或设置自定义导航栏按钮的其他方法有任何建议?

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

只需将此方法添加到UIButton:

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

3 个答案:

答案 0 :(得分:6)

这很直接,你需要为uibutton添加目标而不是uibarbuttonitem。

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

答案 1 :(得分:4)

将动作和目标添加到UIButton,如下所示:

[myButton addTarget:self
             action:@selector(handleMyButtonTap)
   forControlEvents:UIControlEventTouchUpInside];

将动作和目标添加到UIBarButtonItem,如下所示:

[myBarButtonItem setAction:@selector(handleBarButtonTap)];
[myBarButtonItem setTarget:aTarget];

答案 2 :(得分:0)

借助 hgwhittle Mustafa 的答案,我实施了它并且完美无缺 这里是完整的剪辑可以帮助某人

        //Create ImageButton
        UIImage *shareBtnIcon = [UIImage imageNamed:@"dummy_share_icon_22"];

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

        [shareButton addTarget:self action:@selector(shareButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

        //Create BarButton using ImageButton
        UIBarButtonItem *shareBarBtn = [[UIBarButtonItem alloc] initWithCustomView:shareButton];

        //Add BarButton to NavigationBar
        self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:shareBarBtn, nil];

//method for share butto click
-(void) shareButtonClicked:(UIButton*)sender
{
    NSLog(@"you clicked on share button %ld");
}