2011-03-11 102 views
0

是否有可能具有隐形导航栏背景?我以前看过定制的,但是会喜欢关于如何做到这一点的一些指导。隐形导航栏

在此先感谢!

回答

3

要获得一个UINavigationBar的或UIToolbar一个透明背景,您必须将背景色设置为[UIColor clearColor],设置opaque为NO(如果没有的话),并覆盖drawRect不绘制标准渐变背景。第三个是棘手的部分。

如果您直接使用UINavigationBar,您可以很容易地将其子类化,以覆盖drawRect。但我看到你用UINavigation Controller标记了这个,所以你必须尝试用一个类别覆盖它。像这样的东西应该这样做:

@implementation UINavigationBar (invisibleBackground) 

- (void)drawRect:(CGRect)rect {} 

@end 

这具有以下缺点:在您的应用程序的每个导航栏现在有没有背景。如果你希望能够有一些透明和一些正常的,你必须去一步,调酒drawRect所以在需要的时候可以调用原:

#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