在ViewController中设置UINavigationBar背景图像

时间:2013-04-23 21:11:09

标签: iphone ios objective-c uinavigationcontroller

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

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

[[UINavigationBar appearance] setBackgroundImage: navBarImage forBarMetrics:UIBarMetricsDefault];

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

这是我的代码:

- (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];
        }
}

3 个答案:

答案 0 :(得分:6)

使用setBackgroundImage:forBarMetrics:方法:

[navbar setBackgroundImage:[UIImage imageNamed:@"navbar"] 
               forBarMetrics:UIBarMetricsDefault];

答案 1 :(得分:3)

您可以在每个视图中替换默认值:

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,
 self.navigationController.navigationBar.frame.size.width,
 self.navigationController.navigationBar.frame.size.height)];
[imageView setImage:[UIImage imageNamed:@"newImage.png"]];
[self.navigationController.navigationBar addSubview:imageView];
[self.navigationController.navigationBar sendSubviewToBack:imageView];

答案 2 :(得分:0)

试试这个

//创建可调整大小的图像

UIImage *gradientImage44 = [[UIImage imageNamed:@"surf_gradient_textured_44"]
           resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
 UIImage *gradientImage32 = [[UIImage imageNamed:@"surf_gradient_textured_32"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

//设置所有 UINavigationBars

的背景图片
 [[UINavigationBar appearance] setBackgroundImage:gradientImage44 forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage:gradientImage32 forBarMetrics:UIBarMetricsLandscapePhone];