2012-06-06 111 views
2

我在IOS 4+上試過這個代碼,它完美地工作,但直到我的隊友在IOS 5+上測試它爲止。這是代碼將導航欄背景更改爲圖像

@implementation UINavigationBar (CustomImage) 

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

@end 

我需要一個代碼,適用於IOS 4 +和IOS 5+,請幫助我。

回答

3

請試試這個:

@implementation UINavigationBar (CustomImage) 

// Set bar background 
- (UIImage *)customBackground { 
    UIImage *image = [UIImage imageNamed:@"background.png"]; 
    return image; 
} 

- (void)didMoveToSuperview { 
    // Applies to iOS5 only 
    if ([self respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) { 
     [self setBackgroundImage:[self customBackground] forBarMetrics:UIBarMetricsDefault]; 
    } 
} 

// Set the navigation bar background 
- (void)drawRect:(CGRect)rect { 
    [[self customBackground] drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 
} 

@end 

的了setBackgroundImage:forBarMetrics:適用於iOS5的