iPhone中的UINavigationbar背景

时间:2009-09-04 19:33:26

标签: iphone xcode uinavigationbar uinavigationitem

我已将以下代码应用于我的应用程序以更改导航栏图像。

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
[self setNavigationBarTitle];
}
-(void)setNavigationBarTitle {
UIView *aViewForTitle=[[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 45)] autorelease];
UIImageView *aImg=[[UIImageView alloc] initWithFrame:CGRectMake(-8, 0, 320, 45)];
aImg.image=[UIImage imageNamed:@"MyTabBG.png"];
[aViewForTitle addSubview:aImg]; [aImg release]; 
UILabel *lbl=[[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 305, 45)] autorelease];
lbl.backgroundColor=[UIColor clearColor]; lbl.font=[UIFont fontWithName:@"Trebuchet MS" size:22];
lbl.shadowColor=[UIColor blackColor]; [lbl setShadowOffset:CGSizeMake(1,1)];
lbl.textAlignment=UITextAlignmentCenter; lbl.textColor=[UIColor whiteColor]; lbl.text=@"Mobile Tennis Coach Overview";
[aViewForTitle addSubview:lbl];
[self.navigationItem.titleView addSubview:aViewForTitle];
}

参见以下图片。你可以看到我面临的问题。

alt text

<小时/> alt text

我的应用程序的每个视图控制器都有上面的方法来设置导航栏背景。

当我将新的视图控制器推送到我的应用程序时。将出现后退按钮。

我需要后退按钮才会出现。但是图像应该在后面的按钮后面。

现在我对此感到困惑。

你可以帮我解决这个问题吗?

提前感谢您与我分享您的知识。

非常感谢。

2 个答案:

答案 0 :(得分:6)

在一个烦人的夜晚之后,如果你使用drawLayer,我发现了一个轻微的调整。使用drawRect,当您播放视频或YouTube视频时,导航栏将替换为图像。我读了一些帖子,这导致他们的应用被拒绝。

@implementation UINavigationBar (UINavigationBarCategory)

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx 
{
   if([self isMemberOfClass:[UINavigationBar class]])
   {
     UIImage *image = [UIImage imageNamed:@"navBarBackground.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

如果这篇文章准确无误,那么这种方法应该没问题: http://developer.apple.com/iphone/library/qa/qa2009/qa1637.html

答案 1 :(得分:5)

简短的回答是Apple不支持修改UINavigationBar的结构。他们真的不希望你做你想做的事。这就是造成你所看到的问题的原因。

请提交请求此功能的雷达,以便在某些时候获得足够的关注以正式添加。

话虽如此,要解决此问题,您可以使用-drawRect:方法向UINavigationBar添加类别,并在该方法中绘制背景图像。这样的事情会起作用:

- (void)drawRect:(CGRect)rect
{
  static UIImage *image;
  if (!image) {
    image = [UIImage imageNamed: @"HeaderBackground.png"];
    if (!image) image = [UIImage imageNamed:@"DefaultHeader.png"];
  }
  if (!image) return;
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
}
相关问题