将NavigationBar背景更改为图像

时间:2012-06-06 21:06:54

标签: iphone

我在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+的代码,请帮帮我。

1 个答案:

答案 0 :(得分: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