开发者

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?


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.


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).


What about 2 stacked toolbars? Then you can have some system buttons in the top one, and others in the bottom one. If the play button is pressed, then just hide the top toolbar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜