Xavi Valero
Xavi Valero

Reputation: 2057

Cant handle UIBarButtonItem events

I have a UIImageView, which I am adding as the background of a UIBarButtonItem. I make the UIBarButtonItem as the right barbuttonitem of my navigation controller. I am not able to handle the UIBarButtonItem click event as the control doesn't enter the method, while I am debugging. What could be the reason for this?

UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,32,32)];
    [myImage setImage:[UIImage imageNamed:@"logo.png"]];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:myImage];
    //rightBarButton.target = self;
    //rightBarButton.action = @selector(onMyMethod);
    if(isRight){
        self.navigationItem.rightBarButtonItem = rightBarButton;
        self.navigationItem.rightBarButtonItem.target = self;
        self.navigationItem.rightBarButtonItem.action = @selector(onMyMethod);
    }

Upvotes: 1

Views: 4617

Answers (3)

Xavi Valero
Xavi Valero

Reputation: 2057

Going by RIP's answer, I changed the UIBarButtonItem and created a UIButton instead and added it as subview of the navigationcontroller

        UIImage *image = [UIImage imageNamed:@"logo.png"];

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundImage:image forState:UIControlStateNormal];

        [button addTarget:self action:@selector(onMyMethod:)  forControlEvents:UIControlEventTouchUpInside];
        CGRect frame = CGRectMake(260.0, 7.0, 32.0, 32.0);
        button.frame = frame;
        [button setBackgroundImage:image forState:UIControlStateNormal];
        [self.navigationController.navigationBar addSubview:button];

Upvotes: 1

rishi
rishi

Reputation: 11839

I think target and action won't work while using initWithCustomView of UIBarButton, so you can use something like-

UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,32,32)];
[myImage setImage:[UIImage imageNamed:@"logo.png"]];

UIButton* rightButton = [UIButton buttonWithType: UIButtonTypeInfoLight];
[rightButton addTarget:self 
                action:@selector(onMyMethod:) 
      forControlEvents:UIControlEventTouchDown];


UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];

Upvotes: 2

Nikhil Bansal
Nikhil Bansal

Reputation: 1545

Edit your code:

UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,32,32)];
myImage. userInteractionEnabled = Yes;
[myImage setImage:[UIImage imageNamed:@"logo.png"]];
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:myImage];

if(isRight)
{
    self.navigationItem.rightBarButtonItem = rightBarButton;
    self.navigationItem.rightBarButtonItem.target = self;
    self.navigationItem.rightBarButtonItem.action = @selector(onMyMethod:);
}

Try this Thanks :)

Upvotes: 1

Related Questions