navigationbar 的背景顏色和圖片(老外的部落格)
How about a nice navigation bar without default iPhone gradient or with a beautiful background image? Lets do it! The thing we’re going to do in both sub-solutions is to override UINavigationBar drawRect function with a help of category. As you may or may not
know categories helps us to add additional functionality to an existing classes even if we can’t access their source directly. For more information read
UINavigationBar category
First, as I mentioned before, lets override drawRect method with our own. I usually drop this code at the bottom of my application delegate, but you may want to be more organized than that.
?1 2 3 4 |
@implementation
UINavigationBar (UINavigationBarCategory)
-
( void )drawRect:(CGRect)rect
{
}
@end
|
At this point if you run your application (just don’t forget to actually have UINavigationController with visible navigation bar in it) navigation bar will look like.. em.. black rectangle. It means we successfully taken over the control of it’s drawing method and can move further.
Solid color background
So I’ve heard you hate gradients? Since, we’ve already have UINavigationBar in our hands, we can draw a rectangle over it. A nice gray rectangle! Enough of gray already? Okay, red rectangle it will be..
?1 2 3 4 5 6 |
-
( void )drawRect:(CGRect)rect
{
UIColor
*color = [UIColor redColor];
CGContextRef
context = UIGraphicsGetCurrentContext();
CGContextSetFillColor(context,
CGColorGetComponents( [color CGColor]));
CGContextFillRect(context,
rect);
}
|
And just look at our results! Amazing!
But aren’t we forgetting something? We’re not done here yet. Remember that iPhone uses UINavigationBar property tintColor to style buttons in navigation bar, so unless we want blue buttons in red background (just think about poor eyes of your application users!) we need to alter our code a little bit.