0

我有一个具有自定义背景和我自己的后退按钮的UINavigationBar。我做了以下尝试做到这一点。UINavigationItem leftBarButton隐藏在它的背景后面

//custom background 
UIImageView *background = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigation-bar.png"]] autorelease]; 
[self.navigationController.navigationBar insertSubview:background atIndex:0]; 

//custom back button 
UIImage *buttonImage = [UIImage imageNamed:@"btn_back.png"]; 
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button setImage:buttonImage forState:UIControlStateNormal]; 
button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height); 
[button addTarget:self action:@selector(backPressed:) forControlEvents:UIControlEventTouchUpInside]; 
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button]; 
self.navigationItem.leftBarButtonItem = customBarItem; 
[customBarItem release]; 

后退按钮总是有效,但只有当我不应用自定义背景时才能看到。有人可以指出如何实现两者?

在此先感谢。 瑞奇。

回答

1

您可以使用此

@implementation UINavigationBar (UINavigationBarCategory) 

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 
{ 
    if([self isMemberOfClass:[UINavigationBar class]]) 
    { 
     UIImage *image; 


     image=[UIImage imageNamed:@"nav_bar_img"]; 


     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 
+0

非常感谢saadnib,但是如果我想在整个应用程序中更改背景,会发生什么? – Ricky 2011-04-05 06:45:09

+0

放在应用程序委托它将适用于整个应用程序 – saadnib 2011-04-05 07:22:35

+0

对不起,我的意思是我希望导航栏的背景更改为整个应用程序中的不同图像的情况? – Ricky 2011-04-05 07:33:31

0

最后我做了以下一组导航栏的背景图像。

@implementation UINavigationBar (Category) 

- (void)drawRect:(CGRect)rect 
{ 
    MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate]; 
    [delegate.navImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 
} 

@end 

每次我想改变栏的背景,我改变了委托的navImage财产和我的导航栏上调用-setNeedsDisplay

感谢您的帮助。