2012-06-12 45 views
0

我試圖用自定義導航欄實現項目;但是,以下代碼:自定義導航欄iOS 5兼容性

@implementation UINavigationBar (CustomImage) 

// Set the navigation bar background 
- (void)drawRect:(CGRect)rect { 
    UIImage *image = [UIImage imageNamed:@"TopBar.png"]; 
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height + 1)]; 
} 
@end 

不適用於iOS 5.我使用的是Xcode 4.2。

問題:如何實現自定義導航欄而不影響以上版本的代碼的使用(< iOS 5)?

任何幫助,將不勝感激。 :)

回答

3

我終於明白了......這可能會幫助其他人實現這一點。

@implementation UINavigationBar (CustomImage) 

// Set the navigation bar background 
- (UIImage *)barBackground{ 
    UIImage *image = [UIImage imageNamed:@"TopBar.png"]; 
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height + 1)]; 
    return image; 
} 

- (void)didMoveToSuperview{ 
    // Applies to iOS 5 
    if ([self respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) 
    { 
     [self setBackgroundImage:[self barBackground] forBarMetrics:UIBarMetricsDefault]; 
    } 
} 

// This doesn't work on iOS5 but is needed for iOS4 and earlier 
- (void)drawRect:(CGRect)rect 
{ 
    // Draw the image 
    [[self barBackground] drawInRect:rect]; 
} 
@end