如果已经自定义,如何覆盖 UINavigationBar 外观

Lor*_*o B 5 appearance styling uinavigationbar ios ios5

在我的应用程序内的应用程序委托中,我调用以下方法:

- (void)customizeAppearance 
{
    UIImage *gradientPortrait = [[UIImage imageNamed:@"gradient_portrait"] 
        resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

    UIImage *gradientLandscape = [[UIImage imageNamed:@"gradient_landscape"] 
        resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

    [[UINavigationBar appearance] setBackgroundImage:gradientPortrait 
        forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setBackgroundImage:gradientLandscape 
        forBarMetrics:UIBarMetricsLandscapePhone];
}
Run Code Online (Sandbox Code Playgroud)

此代码允许自定义应用程序内的所有导航栏。每个条形都变成绿色,因为我使用的图像是绿色的。

现在我的目标是为特定导航栏覆盖上述配置。特别是,在应用程序生命周期期间,我使用演示样式打开模式控制器UIModalPresentationFormSheet。该控制器出现在一个UINavigationController. 由于我还需要显示附加的导航栏UINavigationController,我想知道如何自定义该栏,而不更改我在应用程序委托中设置的全局配置。

我尝试将tintColor导航栏的属性(以模态方式呈现)设置为[UIColor blackColor]barStyleto UIBarStyleBlack,但它们不起作用。只有栏按钮项目受到影响。

先感谢您。

PS我使用的是iOS 5

Tie*_*eme 4

首先,如果您不介意图像拉伸,则不需要使用 ressizedImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) 方法。

UIImage *gradientPortrait = [UIImage imageNamed:@"gradient_portrait"];
UIImage *gradientLandscape = [UIImage imageNamed:@"gradient_landscape"];

UIImage *someOtherImage = [UIImage imageNamed:@"someOtherImageName"];
Run Code Online (Sandbox Code Playgroud)

然后,为了实现你想要的:

  1. 确保您使用自定义导航栏对 ViewController 进行子类化
  2. 使用以下命令将默认图像添加到所有导航栏

    [[UINavigationBar appearance] setBackgroundImage:gradientPortrait forBarMetrics:UIBarMetricsDefault];
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用以下命令将特定图像添加到导航栏,该导航栏将显示在子类 ViewController 上方

    [[UINavigationBar appearanceWhenContainedIn:[YOURSUBCLASS class], nil] setBackgroundImage:someOtherImage forBarMetrics:UIBarMetricsDefault];
    
    Run Code Online (Sandbox Code Playgroud)

(您可以从应用程序委托中的某个位置调用这些方法)

顺便说一句,如果您只想更改色调颜色,您可以使用tintColor 属性而不是所有图像。

有关更多信息,请查看以下内容的外观部分:UINavigationBar Class Reference