2011-03-11 70 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