Search code examples
iphoneioscustomizationuibarbuttonitemuiappearance

Customizing UIBarButtonItem "Done" style and "Plain" style separately using UIAppearance


I know how to customize UIBarButtonItem using -setBackgroundImage: forState: barMetrics:, but I would like to use different images for UIBarButtonItemStyleDone and UIBarButtonItemStylePlain.

Is there a way to accomplish this using the UIAppearance protocol? Or do I have to set the image each time I want a "Done" style button?

(I tried messing around with code like the following:

[[UIBarButtonItem appearance] setBackgroundImage:image forState:UIControlStateNormal barMetrics:UIBarButtonItemStyleDone];

But that just sets every bar button with the "Done" image.)

Thanks!


Solution

  • In iOS 6 you can use the new method of UIBarButtonItem class:

    - (void)setBackgroundImage:(UIImage *)backgroundImage
                      forState:(UIControlState)state
                         style:(UIBarButtonItemStyle)style
                    barMetrics:(UIBarMetrics)barMetrics
    

    It sets the background image for the specified state, style, and metrics. More details are available in the Apple docs

    So to change the appearance of all UIBarButtonItems you can use something like:

    UIImage *doneBackgroundImage = [[UIImage imageNamed:@"button_done.png"]
       resizableImageWithCapInsets:UIEdgeInsetsMake(0, 4, 0, 4)];
    
    [[UIBarButtonItem appearance] setBackgroundImage:doneBackgroundImage
                                                forState:UIControlStateNormal
                                                   style:UIBarButtonItemStyleDone
                                              barMetrics:UIBarMetricsDefault];