Question

I'm trying to setup a different image (highlighted) when the user press the UIBarButtomItem with this code:

self.addButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"addButton"]
                                                  style:UIBarButtonItemStylePlain
                                                 target:self
                                                 action:@selector(addAlert:)];
[self.addButton setBackgroundImage:[UIImage imageNamed:@"addButtonHigh"]
                              forState:UIControlStateSelected
                            barMetrics:UIBarMetricsDefault];
self.navigationItem.rightBarButtonItem = self.addButton;

But it is not working.

The button appears with the "addButton" image, but when it is pressed the "addButtonHigh" image doesn't appear.

Thank you in advance, Victor

No correct solution

OTHER TIPS

change UIControlState from UIControlStateSelected to UIControlStateHighlighted. If you want to change the background image highlighted. You need to change the UIControlState.

The following is the code snippet i test. it works.

self.addButton = [[UIBarButtonItem alloc] initWithTitle:@"hello" style:UIBarButtonItemStylePlain target:self action:@selector(addAlert:)];

[self.addButton setBackgroundImage:[UIImage imageNamed:@"font_minus_32.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self.addButton setBackgroundImage:[UIImage imageNamed:@"font_plus_32.png"] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];

self.navigationItem.rightBarButtonItem = self.addButton;

Also maybe the following code is the code you wanted.

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundImage:[UIImage imageNamed:@"font_minus_32.png"] forState:UIControlStateNormal];
[btn setBackgroundImage:[UIImage imageNamed:@"font_plus_32.png"] forState:UIControlStateHighlighted];
[btn addTarget:self action:@selector(addAlert:) forControlEvents:UIControlEventTouchUpInside];
[btn sizeToFit];

self.addButton = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.rightBarButtonItem = self.addButton;
- (IBAction)buttonClicked:(id)sender 
{

UIImage *buttonImage = [UIImage imageNamed:@"home.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateHighlighted];

}

UIControlStateHighlighted Highlighted state of a control. A control enters this state when a touch enters and exits during tracking and when there is a touch up event. You can retrieve and set this value through the highlighted property.

UIControlStateSelected Selected state of a control. For many controls, this state has no effect on behavior or appearance. But other subclasses (for example, the UISegmentedControl class) may have different appearance depending on their selected state. You can retrieve and set this value through the selected property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top