在ViewController中设置UINavigationBar背景图像

Jam*_*mes 3 iphone objective-c uinavigationcontroller ios

我可以使用以下代码将导航栏的背景设置为app delegate didFinishLaunchingWithOptions方法中的自定义图像:

UIImage *navBarImage;
navBarImage = [UIImage imageNamed:@"navbar.png"];

[[UINavigationBar appearance] setBackgroundImage: navBarImage forBarMetrics:UIBarMetricsDefault];
Run Code Online (Sandbox Code Playgroud)

我正在尝试在我的应用程序中添加一个选项,以便在切换开关时更改导航栏的背景图像,但它似乎不起作用.是否只能在应用程序启动时设置背景图像?应用程序启动后,我该怎么做?

这是我的代码:

- (void) switchChanged:(id)sender {
    UISwitch* switchView = sender;

        if (switchView.isOn) {
            UIImage *navBarImage = [UIImage imageNamed:@"black_nav.png"];
            [[UINavigationBar appearance] setBackgroundImage: navBarImage forBarMetrics:UIBarMetricsDefault];
        }
        else {
            UIImage *navBarImage = [UIImage imageNamed:@"white_nav.png"];
            [[UINavigationBar appearance] setBackgroundImage: navBarImage forBarMetrics:UIBarMetricsDefault];
        }
}
Run Code Online (Sandbox Code Playgroud)

Den*_*kov 6

使用setBackgroundImage:forBarMetrics: 方法:

[navbar setBackgroundImage:[UIImage imageNamed:@"navbar"] 
               forBarMetrics:UIBarMetricsDefault];
Run Code Online (Sandbox Code Playgroud)