3

我可以使用以下代码在应用程序委托 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];
        }
}
4

3 回答 3

6

使用setBackgroundImage:forBarMetrics: 方法:

[navbar setBackgroundImage:[UIImage imageNamed:@"navbar"] 
               forBarMetrics:UIBarMetricsDefault];
于 2013-04-23T21:14:57.497 回答
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];
于 2013-04-23T21:33:45.170 回答
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];
于 2013-04-23T21:54:40.693 回答