Invisible Navigation Bar
Is it possible to have an invisible navigation bar background?开发者_StackOverflow I've seen custom ones before, but would love some guidance on how to do this.
Thanks in advance!
To get a transparent background on a UINavigationBar or UIToolbar, you have to set the background color to [UIColor clearColor]
, set opaque
to NO (if it isn't already), and override drawRect
to not draw the standard gradient background. The third is the tricky part.
If you're using UINavigationBar directly, you can easily enough just subclass it to override drawRect
. But I see you tagged this with UINavigationController, so you'll have to try overriding it with a category. Something like this should do it:
@implementation UINavigationBar (invisibleBackground)
- (void)drawRect:(CGRect)rect {}
@end
That has the drawback that every navbar in your app will now have no background. If you want to be able to have some transparent and some normal, you have to go one step further and swizzle drawRect
so you can call the original when needed:
#import <objc/runtime.h>
@implementation UINavigationBar (invisibleBackgroundSwizzle)
// The implementation of this method will be used to replace the stock "drawRect:". The old
// implementation of "drawRect:" will be attached to this name so we can call it when needed.
- (void)replacementDrawRect:(CGRect)rect {
if (![self.backgroundColor isEqual:[UIColor clearColor]]) {
// Non-transparent background, call the original method (which now exists
// under the name "replacementDrawRect:"). Yes, it's a bit confusing.
[self replacementDrawRect:rect];
} else {
// Transparent background, do nothing
}
}
// This special method is called by the runtime when this category is first loaded.
+ (void)load {
// This code takes the "drawRect:" and "replacementDrawRect:" methods and switches
// thier implementations, so the name "drawRect" will now refer to the method declared as
// "replacementDrawRect:" above and the name "replacementDrawRect:" will now refer
// to the original implementation of "drawRect:".
Method originalMethod = class_getInstanceMethod(self, @selector(drawRect:));
Method overrideMethod = class_getInstanceMethod(self, @selector(replacementDrawRect:));
if (class_addMethod(self, @selector(drawRect:), method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
class_replaceMethod(self, @selector(replacementDrawRect:), method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, overrideMethod);
}
}
@end
I was looking this up myself (again) just today, some good blog posts about this topic are:
http://atastypixel.com/blog/making-uitoolbar-and-uinavigationbars-background-totally-transparent/
http://idevrecipes.com/2011/01/12/how-do-iphone-apps-instagramreederdailybooth-implement-custom-navigationbar-with-variable-width-back-buttons/
精彩评论