Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change (not init) a UIBarButtonItem identifier programmatically?

In IB I can set the identifier of a UIBarButtonItem to 'play' which adds an image of a play button (right-pointing triangle).

Is there a way to change this image programmatically? I want to change it to 'pause' when the play button is pressed.

I know you can initialize a UIBarButtonItem with an identifier but I've yet to find a way to change it after it's been initialized. Is this even possible?

The only thing I can think of is to remove the old button and initialize a new one in its place, but this hardly seems efficient.

Any thoughts?

like image 957
nebs Avatar asked Jun 16 '10 15:06

nebs


2 Answers

Ok I've googled this question to death and ran into sample code from Apple where they do exactly the same thing (toggle play/pause button graphic on a toolbar button). But instead of using the built in play and pause identifiers of UIBarButtonItem they use a custom UIButton and toggle custom images.

So if Apple goes through the trouble of creating and toggling custom images on a UIButton instead of the built in play and pause UIBarButtonItem buttons then I think it's pretty safe to say there's no way to programatically change the identifier of a UIBarButtonItem.

This is what they (Apple) do to toggle the images when the button is pressed:

// Call this when the button you want to toggle is pressed:
[playButton setImage:((p.playing == YES) ? pauseBtnBG : playBtnBG) forState:UIControlStateNormal];

Replace p.playing with whatever BOOL you want to hold the state of your button. playButton is the custom UIButton in the toolbar. pauseBtnBG and playBtnBG are the images to toggle.

like image 163
nebs Avatar answered Oct 12 '22 23:10

nebs


This seems to work fairly well:

UIBarButtonItem *oldButton = [myToolBar.items objectAtIndex:1];
[myToolBar setItems:[NSArray arrayWithObjects:[myToolBar objectAtIndex:0], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(tapStopRefreshButton:)],nil] animated:NO];
[oldButton release];

In this example I had a toolbar for a UIWebView and when someone clicked Reload I wanted it to change to Stop. The toolbar only had a flexible space and the one button on it - to right-align the button - so I grabbed a reference to the old button, made a new one with the same selector as the old, reset the buttons on the tab bar, and then released the original button.

Not the prettiest, but you can use all standard buttons without having to override the button class(es).

like image 29
jimmy0x52 Avatar answered Oct 12 '22 23:10

jimmy0x52