【问题标题】:Objective-C: Background image and title in Navigation BarObjective-C:导航栏中的背景图像和标题
【发布时间】:2010-11-26 09:55:09
【问题描述】:

我的导航栏中需要背景图片和标题。对于图片我写了一个类别:

@implementation UINavigationBar(MyNavigationBar)
- (void)setBackgroundImage {
    UIImageView *aTabBarBackground = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"navBarBackgrd.png"]];
    [self addSubview: aTabBarBackground];
    [self sendSubviewToBack: aTabBarBackground];
    [aTabBarBackground release];
}
@end

我在我的 AppDelegate 中调用了这个类别,并且在整个应用程序中都有背景图片:

[navigationController.navigationBar setBackgroundImage]; 

每个 ViewController 都有一个标题:

[self setTitle:@"MyTitle"];

但是设置了背景图片后,标题出现了问题。

在每个作品的第一个视图中,我看到了背景图片和标题 :-) 但在下一个视图中,标题消失了。只有背景图像可见。也许标题在图片下方?

从技术上讲,两者都可以显示。有了这个技巧,它就起作用了:

  1. 在打开下一个 ViewController 之前隐藏导航栏:

    [self.navigationController setNavigationBarHidden:YES];

  2. 在下一个 ViewController 中显示导航栏:

    [self.navigationController setNavigationBarHidden:NO];

现在,图像和标题是可见的,但这个解决方案不是最好的 ;-)

【问题讨论】:

    标签: objective-c uinavigationbar background-image title navigationbar


    【解决方案1】:

    我明白了!

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

    Background image for navigation view

    【讨论】:

      【解决方案2】:

      IOS5之后你应该这样做,例如在AppDelegate中


       UIImage *img = [[UIImage imageNamed:@"image.png"]resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
      [[UINavigationBar appearance] setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
      [[UINavigationBar appearance] setBarStyle:UIBarStyleBlackTranslucent];
      [[UINavigationBar appearance] setTintColor:[UIColor colorWithRed:0 green: 0 blue:0  alpha:1]];
      

      【讨论】:

      • 但您不能使用此代码设置titleview :-|。您必须为此创建类别。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多