0

我试图用自定义导航栏实现一个项目;但是,以下代码:

@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)的情况下实现自定义导航栏?

任何帮助,将不胜感激。:)

4

1 回答 1

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
于 2012-06-12T22:48:18.753 回答