Can't set a background image to UINavigationCo

2019-07-26 17:12发布

问题:

I've added an image to my project. Strangely, on the filesystem it is located in the root directory of the application, while in the project explorer within XCode I've put it in /Images/navbar-bg.png. How to make this consistent?

By the way, I want o add it as background image to my UINavigationController. This is the code, but I see no changes from the default blue background:

// navigation
navigationController = [[UINavigationController alloc] initWithRootViewController:cardListViewController];
// ps hue: 37, 53, -5
navigationController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"navbar-bg" ofType:@"png"]]];

self.window.rootViewController = navigationController;

I've also tried UIImage imageNamed with no results. I want to do it programmatically and I'm not using any xib here.

Thanks

回答1:

Those yellow-looking folder icons you see in XCode's project explorer don't actually represent folders; they are groups. You can, of course, move the file out of the Images subfolder to make it consistent, but I presume you want to do the reverse.

To add items to your project and have them retain their source folder name, you have to create 'folder references'. In the Add Files... dialog, choose the "Create folder references for any added folders" radio button. You'll get a blue folder icon instead of a yellow one; all items in that folder will get added to your project, and any time you change the contents of that folder, the built executable will match its contents.

... and, you asked a second question ...

In iOS 5, to add an image to a navigation bar, use UINavigationBar:setBackgroundImage.



回答2:

If it is the background colour of the navigation controller, then any controller being displayed in the navigation controller will be displayed on top of it. This means it will never be visible. What you are seeing is the cardlistcontroller, you will have to set the background image on this controller instead.



回答3:

Try this, Write this code in your viewDidload method. Thats it

UINavigationBar *navigationBar = self.navigationController.navigationBar;
UIImage *image = [UIImage imageNamed: @"NavBar-Wood.png"];
[navigationBar setBackgroundImage:image forBarMetrics: UIBarMetricsDefault];
self.navigationController.navigationBar.tintColor = [UIColor brownColor];

Thanks.