导航栏在横屏模式下的自定义背景

7
我正在为我的UINavigationBar添加自定义背景。 只要手机处于竖屏模式,它就可以正常工作。 一旦我切换到横屏模式,一半的栏变成了蓝色(默认的导航栏颜色),另一半是我的图像。
如何在横屏模式下拉伸图像,并使其在竖屏模式下变小?
谢谢
解决方案: 如果有人正在寻找如何向导航栏添加图像的答案-这里是
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 480.0, 44.0)];
[imgView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"navbar_landscape" ofType:@"png"]]];
[navigationController.navigationBar addSubview:imgView];
[imgView release];

我不得不将第二行更改为: [imgView setImage:[UIImage imageNamed:@"navbar.png"]]; ...以防有人遇到noshow问题。 - maralbjo
谢谢,哦,这篇文章有点旧了,不管怎样...那么更改navigationBar的高度怎么办?在这种情况下,我应该创建子类吗? - aneuryzm
6个回答

6

经过一些研究和试错,我找到了一个解决方法,可以在进入电影播放模式时不替换导航栏。希望这不会引起应用程序审批方面的问题,但根据这篇文章,我认为应该没问题:

http://developer.apple.com/iphone/library/qa/qa2009/qa1637.html

@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

6
在两种屏幕方向模式下,最好使用
[navigationController.navigationBar insertSubview:imgView atIndex:0];

这将图像视图放置在所有其他视图之下,并且所有默认导航栏元素(标题,标准按钮)均正常工作。

3

您可能需要设置背景图像视图的自动调整大小掩码;尝试使用 UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight


1

您可以通过检查UINavigation栏实例的框架大小,为不同方向提供不同的图像来更改肖像和风景方向的图像:

- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    if ([self isMemberOfClass:[UINavigationBar class]] == NO) {
        return;
    }

    UIImage *image = (self.frame.size.width > 320) ?
                        [UINavigationBar bgImageLandscape] : [UINavigationBar bgImagePortrait];
    CGContextClip(context);
    CGContextTranslateCTM(context, 0, image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), image.CGImage);
}

这个完整的Xcode演示项目自定义UINavigationBar外观可能会有所帮助。它还包括@2x版本的背景图像,以支持iPhone 4设备上的Retina显示屏。


1
这绝对是我见过的最好、最全面的解决方案,你在Github上的示例项目也非常出色。谢谢你。 我鼓励每个人都给它投票。 - memmons
非常感谢。我很高兴你觉得它有用。 - Ahmet Ardal

1
Ben提供的解决方案确实解决了问题,但它会在横向模式下拉伸图像。最终我创建了两个图像-一个用于横向模式,另一个用于纵向模式。然后我添加了代码到shouldAutoRotate中,根据方向改变导航栏图像。

0

尝试使用更简单的方法[UIImage imageNamed:@"navbar_landscape.png"],因为UI元素正是imageNamed:旨在使用的,就像ljonesATL所展示的那样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接