Adding action and target to a custom Navigation BarButtonItem?

帅比萌擦擦* 提交于 2019-11-30 20:54:15

It's pretty straight forward, you need to add target for uibutton not for 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.

hgwhittle

Add an action and target to a UIButton like this:

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

Add an action and target to a UIBarButtonItem like this:

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

With the help of answers by hgwhittle and Mustafa I implemented and it works perfect here is the complete snip may help someone

        //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");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!