Updating UIImage on UiBarButtonItem from identifier to image
I think this should work.
-(IBAction)buttonClick:(UIBarButtonItem *)sender {
if ([[sender backgroundImageForState:UIControlStateNormal barMetrics:UIBarMetricsDefault] isEqual:[UIImage imageNamed:@"Play.jpg"]]) {
[sender setBackgroundImage:[UIImage imageNamed:@"Pause.jpg"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
}else{
[sender setBackgroundImage:[UIImage imageNamed:@"Play.jpg"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
}
}
Of course, you'll have to set the background image initially (in viewDidLoad) to the "Play" image for this to work.
After Edit:
If you want to use the system play and pause button, as far as I know, you have to replace the button. I don't think there's a way to just change the image. So, I did it this way. The button was set up in IB with the outlet playPauseButton, and the action playClick. I also made an outlet to the tool bar (toolBar).
-(IBAction)playClick:(UIBarButtonItem *)sender {
UIBarButtonItem *pause = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(pauseClick:)];
NSMutableArray *tbItems = [self.toolBar.items mutableCopy];
[tbItems removeObject:self.playPauseButton];
self.playPauseButton = pause;
[tbItems addObject:pause];
self.toolBar.items = tbItems;
}
-(void)pauseClick:(UIBarButtonItem *)sender {
UIBarButtonItem *play = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(playClick:)];
NSMutableArray *tbItems = [self.toolBar.items mutableCopy];
[tbItems removeObject:self.playPauseButton];
self.playPauseButton = play;
[tbItems addObject:play];
self.toolBar.items = tbItems;
}
If the button is already created and you have an outlet for it, you can simply set it like this:
UIImage* backgroundImage = [UIImage yourImage];
[self.barButtonItem setImage:backgroundImage];
Works like charm.