2

I used the following code to set the image "Sample" as a background color of my UIToolbar

self.toolbar.layer.contents = (id)[UIImage imageNamed:@"Sample.png"].CGImage;

But it seems the above one does not works with iOS5.1 and the default background color of UIToolbar appeared. I doesn't have any problem with this line in iOS4.

Am I missing something? Please suggest me the reason..

Thanks

Confused
  • 3,846
  • 7
  • 45
  • 72

3 Answers3

7

The correct way, which works from the app delegate (unlike the solution above) and which is also marked with UI_APPEARANCE_SELECTOR in the header files, is:

[[UIToolbar appearance] setBackgroundImage:bgImage forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
[[UIToolbar appearance] setBackgroundImage:bgImage forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsLandscapePhone];
Andres Kievsky
  • 3,461
  • 32
  • 25
4

enter image description here

// Create resizable images
UIImage *gradientImage44 = [[UIImage imageNamed:@"imageName.png"] 
                            resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
// Set the background image for *all* UINavigationBars
[[UIToolbar appearance] setBackgroundImage:gradientImage44 
                                   forBarMetrics:UIBarMetricsDefault];

Better to use appearance API introduced with iOS 5. May this will help you

Kuldeep
  • 2,589
  • 1
  • 18
  • 28
  • Thanks! Just a note that this must be done in a view controller somewhere, I was trying it in the app delegate and it wasn't working for a while... – ekinnear Aug 01 '12 at 17:24
  • Any suggestions how to do this in AppDelegate to create different toolbar backgrounds for different screens?.. – dreamzor Jan 10 '13 at 18:09
  • See my solution for a correct way to do this, that also works from the app delegate. – Andres Kievsky Feb 07 '13 at 04:39
1

setBackgroundImage:forToolbarPosition:barMetrics: this is used to set the image to use for the background in a given position and with given metrics.,

In your case

// Set the background image for PortraitMode
[self.toolbar setBackgroundImage:[UIImage imageNamed:@"Sample.png"] 
                                   forBarMetrics:UIBarMetricsDefault];
// and For LandscapeMode
[self.toolbar setBackgroundImage:[UIImage imageNamed:@"Sample.png"] 
                                   forBarMetrics:UIBarMetricsLandscapePhone];
Bala
  • 2,895
  • 1
  • 19
  • 60