Reputation: 1675
I'm using the category to customize nav bar. My code is:
- (void) drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColor(context, CGColorGetComponents([self.tintColor CGColor]));
CGContextFillRect(context, rect);
}
It works well, but not in iOS 5. I need nav bar color to be solid without any gradient. How should I do this?
As I know, for iOS 5 the only way to replace drawRect
method is to make a subclass, but is there any way to make all navigation controllers to use UINavigationBar
subclass instead of original class?
Upvotes: 3
Views: 7616
Reputation: 389
This is more of a hack and has consistently worked for me. This needs to be in the AppDelegate file.
//Create a size struct.
CGSize size = CGSizeMake(768, 50);
//CReate a imagecontext from a non-existing image. You can use a existing image as well, in that case the color will be the color of the image.
UIImage *backgroundImage = [UIImage imageNamed:@"nonexist.png"];
UIGraphicsBeginImageContext(size);
[backgroundImage drawInRect:CGRectMake(0,0,size.width,size.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.navigationController = [[UINavigationController alloc]initWithRootViewController:self.viewController];
Set the background color to be the color of your choice.
[self.navigationController.view setBackgroundColor:[UIColor blackColor]];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
//Most important line.
[navigationController.navigationBar setBackgroundImage: newImage forBarMetrics:UIBarMetricsDefault];
Upvotes: 0
Reputation: 31
This covers both iOS 5 and iOS 4.3 and earlier
https://gist.github.com/1774444
Upvotes: 1
Reputation: 4267
In iOS 5 you can use the UIAppearance protocol to set the appearance of all UINavigationBars in your app. Reference: link.
The way I got a solid color was to create a custom image for the navigation bar, and set it as UINavigationBars background. You might have to create the image with the same size as the UINavigationBar, at least that's what I did.
In your app delegate, do something like this:
UIImage *image = [UIImage imageNamed:@"navbarbg.png"];
[[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
You also have to add the UIAppearanceContainer
protocol to the header file:
@interface AppDelegate : UIResponder <UIApplicationDelegate, UIAppearanceContainer>
@end
You can probably achieve the same thing by setting some color or something, instead of an image. But I found this to be an easy solution.
Upvotes: 13