Reputation: 2342
I am trying to set a background image for UINavigationBar. I have done it many times in Objective-C but in swift, I am facing a problem. I have searched and tried many things but none did work for me.
Here is the code I am using:
let navBackgroundImage:UIImage! = UIImage(named: "header")
self.navigationController?.navigationBar.setBackgroundImage(navBackgroundImage, for: .default)
My header image has following dimensions:
375 × 64 for 1x and so on for 2x and 3x. I have tried with 320x64 as well, but still, it doesn't work.
Screenshot:
As you can see, the image is appearing twice and not covering complete width.
Any suggestions?
EDIT
After trying
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "header")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .stretch), for: .default)
Upvotes: 0
Views: 425
Reputation: 5684
Try this,
Swift
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "header")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .stretch), for: .default)
Objective C
[self.navigationController.navigationBar setBackgroundImage:[[UIImage imageNamed:@"header"] resizableImageWithCapInsets: UIEdgeInsetsMake(0, 0, 0, 0) resizingMode: UIImageResizingModeStretch] forBarMetrics:UIBarMetricsDefault];
Upvotes: 2
Reputation: 3606
First add this line in your appDelegate didFinishLaunchingWithOptionsMethod
UINavigationBar.appearance().barTintColor = UIColor.clear
Then add the following in viewDidLoad
method
if let image = UIImage(named: "header") {
UINavigationBar.appearance().setBackgroundImage(image.resizableImage(withCapInsets:UIEdgeInsets.zero, resizingMode: .stretch), for: .default)
UINavigationBar.appearance().contentMode = .scaleAspectFill
}
Upvotes: 0
Reputation: 1
You should use a debug point to make sure the code does not run twice, then:
let navBackgroundImage = UIImage(named: "header")!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch)
navigationController?.navigationBar.setBackgroundImage(navBackgroundImage, for: .default)
Upvotes: 0
Reputation: 312
Try print something or use debug point to sure that your code not called twice, or use
let navBackgroundImage:UIImage! = UIImage(named: "header")!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch)
UINavigationBar.appearance().setBackgroundImage(navBackgroundImage, for: .default)
Upvotes: 0