Luca
Luca

Reputation: 1874

Use custom background with UINavigationController default UIToolbar

I want to use my self background for my UIToolbar.

To do that with the UINavigationBar I've just used this category with the override of the drawRect method:

    @implementation UIToolbar (CustomImage)

    - (void)drawRect:(CGRect)rect {
         UIImage *image = [UIImage imageNamed: @"nm010400.png"];
         [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    }
    @end

This piece of code works perfectly for the UINavigationBar but this does not work for the UIToolbar that is inncluded in the UINavigationController and enabled with this line o code:

self.navController.toolbarHidden = NO;

Can anyone help me with the problem? I' m sure that the UINavigationController use a standard UIToolbar so why this not works?!? thanks

Upvotes: 2

Views: 3852

Answers (2)

user1141476
user1141476

Reputation: 61

In your custom UINavigationController's viewDidLoad use the following code:

[self.toolbar setBackgroundImage:[UIImage imageNamed:@"mytoolbarbg.png"] 
              forToolbarPosition:1 
              barMetrics:UIBarMetricsDefault];

Upvotes: 1

Scott Sherwood
Scott Sherwood

Reputation: 3128

To create custom UI elements there is no need to create categories anymore. With IOS 5 you can change the appearance of any UI element through the UIApperance protocol. You can change individual UI elements as normal but the real power comes when you are creating a themed application. Using this new protocol you can change the style of all instances of a particular UI element or even a UI element in a particular setting such as a UIBarButtonItem in a UINavigationController.

To change the appearance of all of the UINavigationBars in your application you can set the background like so,

[[UINavigationBar appearance]setBackgroundImage:[UIImage imageNamed:@"myNavBar.png"] forBarMetrics:UIBarMetricsDefault];

you change different attributes depending on which element you are using to change the title attributes of the UINavigationBar you can use,

[[UINavigationBar appearance] setTitleTextAttributes:
  [NSDictionary dictionaryWithObjectsAndKeys:
  [UIColor whiteColor], UITextAttributeTextColor, 
  [UIFont fontWithName:@"MarkerFelt-Thin" size:24], UITextAttributeFont, nil]];

you can also use this on other UI elements so to change the background on all instances of the UIToolbar you can call

[[UIToolbar appearance] setBackgroundImage:[UIImage imageNamed:@"myToolBar.png"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];

Hope this helps.

Upvotes: 2

Related Questions