【问题标题】:UINavigationBar background image does not change with rotationUINavigationBar 背景图片不随旋转而改变
【发布时间】:2012-04-30 12:58:39
【问题描述】:

我正在尝试使用 iOS 5 中的外观方法来使用背景图像。我正在使用以下语句设置背景图像:

UIImage *portraitImage = [UIImage imageNamed:@"test_bar_portrait.png"];
UIImage *landscapeImage = [UIImage imageNamed:@"test_bar_landscape.png"];
[[UINavigationBar appearance] setBackgroundImage:portraitImage forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage:landscapeImage forBarMetrics:UIBarMetricsLandscapePhone];

当我运行应用程序时,正确的图像显示为纵向和横向,但当我旋转回纵向时,它仍然显示横向图像。

我在这里创建了一个示例测试应用程序: http://dl.dropbox.com/u/7834263/Appearance%20Test.zip

以及正在发生的事情的屏幕截图:

【问题讨论】:

    标签: iphone ios uiimage uiappearance


    【解决方案1】:

    我尝试将您的代码更改为以下代码,它对我来说效果很好。

    UIImage *portraitImage = [UIImage imageNamed:@"test_bar_portrait.png"];
    UIImage *landscapeImage = [UIImage imageNamed:@"test_bar_landscape.png"];
    [[UINavigationBar appearance] setBackgroundImage:portraitImage forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setBackgroundImage:landscapeImage forBarMetrics:UIBarMetricsLandscapePhone];
    
    self.navigationController.navigationBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    

    请检查一下。

    【讨论】:

    • 谢谢,这可以解决问题。但由于我在我的应用程序中使用 AutoLayout,使用 autoresizingMask 是否安全?据我所知,当我们使用 AutoLayout 时,我们不使用 autoresizingMask。如果我错了,请纠正我。
    • Autolayout 可以与 autoresizingMask 一起使用。您正在 autoresizingMasks 将被翻译成自动布局。参见 UIView 属性:translatesAutoresizingMaskIntoConstraints
    【解决方案2】:

    Swift 2.0:

    let portraitImage: UIImage = UIImage(named: "Navbar.portrait.png")!
    let landscapeImage: UIImage = UIImage(named: "Navbar.landscape.png")!
    UINavigationBar.appearance().setBackgroundImage(portraitImage, forBarMetrics: .Default)
    UINavigationBar.appearance().setBackgroundImage(landscapeImage, forBarMetrics: .CompactPrompt)
    self.navigationController!.navigationBar.autoresizingMask = .FlexibleTopMargin
    

    【讨论】:

    • 对我来说,只有.Compact bar metric 适用于横向模式