5

How can I remove the default gradient on a UINavigationBar? What property do I set to do this?

CodeGuy
  • 28,427
  • 76
  • 200
  • 317

1 Answers1

23

You can remove the gradient and set your own solid color by popping this code into the class that has the navigation bar. You can change the UIColor to whatever color you need. Note that this code needs to be outside of another implementation, so whatever .m file you put it in put it before the @implmentation of the class already implemented in that file.

@implementation UINavigationBar (UINavigationBarCategory)   
- (void)drawRect:(CGRect)rect {
UIColor *color = [UIColor blueColor];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColor(context, CGColorGetComponents( [color CGColor]));
CGContextFillRect(context, rect);
}   
@end
Nitrex88
  • 2,158
  • 2
  • 21
  • 23
  • In my application, I have two UINavigationBars. I want one to keep the gradient, and I want one to not have the gradient. How could I do this? (this code works by the way, but it makes both of the bars have no gradient) – CodeGuy Feb 05 '11 at 03:32
  • In order to have the two different behaviors you are looking for you will need to have two custom subclasses of UINavigationBar. In one subclass you override the drawRect method like I did in the above implementation. In the other subclass you just don't define the drawRect method and you won't override the original gradient effect. let me know if you get it working. – Nitrex88 Feb 05 '11 at 06:00
  • 9
    It's been a few months, but is there any chance you can mark my answer as correct? I need some reputation so I can put a bounty on one of my questions...thanks – Nitrex88 May 24 '11 at 00:29
  • 1
    So I'm attempting to do this, but it does not appear to make a difference in what is happening with my UINavigationBar. my code is `@implementation UINavigationBar (UINavigationBarCategory) - (void)drawRect:(CGRect)rect { UIColor *color = NAVBAR_TINT; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColor(context, CGColorGetComponents( [color CGColor])); CGContextFillRect(context, rect); } @end` Is this method no longer valid? I'm having trouble getting any of the solutions I've found to work. – bplattenburg Apr 10 '13 at 21:15
  • 3
    In case anyone else finds this, it seems that in iOS 5.0 they removed drawRect from the UINavigationBar, so there is a different method for newer iOS revisions - see http://stackoverflow.com/questions/7657465/uinavigationbars-drawrect-is-not-called-in-ios-5-0 – bplattenburg Apr 11 '13 at 15:33