You can use a UIButton
as a customView
of a UIBarButtonItem
and have two different background images for a normal
and selected
state of the UIButton. Then when the button is tapped, you can just set the selected
state to YES
or NO
.
// Build right bar button
UIImage *normalButtonImage = [UIImage imageNamed:@"normal-button"];
UIImage *selectedButtonImage = [UIImage imageNamed:@"selected-button"];
CGRect rightButtonFrame = CGRectMake(0, 0, normalButtonImage.size.width,
normalButtonImage.size.height);
UIButton *rightButton = [[UIButton alloc] initWithFrame:rightButtonFrame];
[rightButton setBackgroundImage:normalButtonImage forState:UIControlStateNormal];
[rightButton setBackgroundImage:selectedButtonImage forState:UIControlStateSelected];
[rightButton addTarget:self action:@selector(rightBarButtonPress)
forControlEvents:UIControlEventTouchDown];
[orientationButton setShowsTouchWhenHighlighted:YES];
[orientationButton setSelected:NO];
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
[self.navigationItem setRightBarButtonItem:rightBarButton];
Then your in method for when the button is clicked, change the state
- (void)rightBarButtonPress
{
//toggle selected state of button
UIBarButtonItem *rightBarButton = self.navigationItem.rightBarButtonItem;
UIButton *button = (UIButton *)rightBarButton.customView;
[button setSelected:!button.selected];
//do whatever else you gotta do
}