导航和工具栏自定义背景图像在IOS 5中不起作用

时间:2011-12-20 04:51:35

标签: iphone

我已经使用xcode 4(ios 4.3)在我们的项目中实现了自定义导航和工具栏,并且它在那里工作正常,但现在我已经更新了我的xcode 4.2(ios 5),这里它不起作用。事情有点奇怪,请帮助这个

这是我的应用委托代码

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @"TopBg_with_logo.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

@implementation UIToolbar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @"btmbar_Bg.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

2 个答案:

答案 0 :(得分:1)

在您继承UINavigationBar并在那里调用drawRect之前,不会调用

drawLayer或drawRect方法。

遵循此代码 -

@implementation UINavigationBar (UINavigationBarCategory)

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 
{




        if([self isMemberOfClass:[UINavigationBar class]])
        {
            UIImage *image;


            image=[UIImage imageNamed:@"title_768.png"];



            CGContextClip(ctx);
            CGContextTranslateCTM(ctx, 0, image.size.height);
            CGContextScaleCTM(ctx, 1.0, -1.0);
            CGContextDrawImage(ctx,
                               CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage); 


        }
        else 
        {        
            [super drawLayer:layer inContext:ctx];     
        }

}  
@end

在代码中添加MyNavigationBar.h和MyNavigationBar.m文件 -

MyNavigationBar.h -

#import <Foundation/Foundation.h>

@interface MyNavigationBar : UINavigationBar <UINavigationBarDelegate>

@end

MyNavigationBar.m -

#import "MyNavigationBar.h"

@implementation MyNavigationBar

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{



    UIImage *image;

    image=[UIImage imageNamed:@"title_768.png"];


    [image drawInRect: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) ];


}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{

}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
}


@end

现在使用MyNavigationBar将您的UINavigationBar子类化。

答案 1 :(得分:0)

在这种情况下使用此代码:

float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 5.0) {
        UINavigationBar *navBar = self.navigationController.navigationBar;
        UIImage *image = [UIImage imageNamed:@"topbar.png"];
        [navBar setBackgroundImage:image forBarMetrics:UIBarStyleDefault];   
    }