How do you set a custom background image for the large title NavigationBar in iOS 11? I'm using a custom subclass which I've assigned to the navigationControllers in the storyboard.
This is how I create my custom NavBar:
class CustomNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationBar.tintColor = UIColor(red:1, green:1, blue:1, alpha:0.6)
self.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
if #available(iOS 11.0, *) {
self.navigationBar.prefersLargeTitles = true
self.navigationItem.largeTitleDisplayMode = .automatic
self.navigationBar.largeTitleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
self.navigationBar.barTintColor = UIColor.green
}
self.navigationBar.isTranslucent = false
self.navigationBar.setBackgroundImage(#imageLiteral(resourceName: "navigationBarBackground"), for: .default)
self.navigationBar.shadowImage = #imageLiteral(resourceName: "navigationBarShadow")
}
}
Strangely the setBackgroundImage(image, for: .default)
doesn't work for the large titles. It worked before with iOS 10 and also if I rotate the iPhone (and activate the small NavBar) the background is back?
Edit:
The backgroundImage
is still rendered but somehow hidden. Only if you start scrolling and the "normal" Navigation Bar appears, the backgroundImage is visible. Also the barTintColor
is completely ignored in this case.
I had the same issue, fixed it by
Remove setBackgroundImage and use barTint color with pattern image
Get image with gradient colors
In iOS 11 you no more need set BackgroundImage(Remove its declaration) if you use large titles. Instead you need use BarTintColor.
Try this code (Swift 4.0):
in viewDidLoad()
Changing the barTint didn't work for me so I change the layer inside navigationBar
In Xamarin it would be like this:
The this.View.Layer.Insert is optional. I need it when I'm "curling" up and down an image on the NavigationBar
Piggybacking on oldrinmendez's answer - that solution works perfect for a horizontal gradient.
For a VERTICAL gradient, I was able to use the same function from oldrinmendez's answer by calling it again in scrollViewDidScroll. This continually adjusts the height of the gradient image as the user scrolls.
Start with the function from oldrinmendez :
Create an update function to call it with the options you want:
Finally add the update function to scrollViewDidScroll & ViewDidApper: Use ViewDidAppear so the correct navigation bar height is returned