Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIBarButtonItem init with custom view selector not working properly

I'm trying for hours to make a left button work properly and mimic a back button.

My code to create the button:

UIBarButtonItem *backButton = [self customBarButton:@"back_button" imageHiglighted:@"settings_button_highlighted" x:20 y:0 widthDivider:2.6 heightDivider:2.6];

backButton.target = self;
backButton.action = @selector(buttonPressed:);

self.navigationItem.leftBarButtonItem = backButton;

Here the method called to create custom button:

- (UIBarButtonItem *)customBarButton:(NSString *)imageDefault imageHiglighted:(NSString *)imageHighlighted x:(float)x y:(float)y widthDivider:(float)widthDivider heightDivider:(float)heightDivider {

UIImage *customImageDefault = [UIImage imageNamed:imageDefault];
UIImage *customImageHighlighted = [UIImage imageNamed:imageHighlighted];

CGRect frameCustomButton = CGRectMake(x, y, customImageDefault.size.width/widthDivider, customImageDefault.size.height/heightDivider);

UIButton *customButton = [[UIButton alloc] initWithFrame:frameCustomButton];

[customButton setBackgroundImage:customImageDefault forState:UIControlStateNormal];
[customButton setBackgroundImage:customImageHighlighted forState:UIControlStateHighlighted];

UIBarButtonItem *barCustomButton =[[UIBarButtonItem alloc] initWithCustomView:customButton];

return barCustomButton;

}

And the action:

-(void)buttonPressed:(id) sender{

    NSLog(@"Entered");
    SearchViewController *ViewController = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:ViewController animated:YES];

}

So I was able to make it with a simple UIButton but not with a UIButtonBarItem and I really don't know what's going on with it.

If you could help me I'd be very grateful.

Thanks.

like image 372
Roger Fernandez Guri Avatar asked Dec 07 '22 12:12

Roger Fernandez Guri


1 Answers

Do this add selector to custom button as it is view of bar buttom:

[customButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

EDIT : Note : the target and action of the UIBarButtonItem apply to custom views.

like image 82
Paresh Navadiya Avatar answered Mar 23 '23 01:03

Paresh Navadiya