Simple way to make navigation bar , Transparent.
by nikesh on 21/11/15 at 2:06 pm
During my last ios application development , I needed a transparent navigation bar. I could do this by creating my own navigation bar and using push and pop mechanism to handle viewcontrollers. But then I found very interesting solution for making default navigation bar transparent.
So For demo purpose .. I have setup a project, added a viewcontroller and embed that view in a navigation controller
Now I want to make this navigation bar transparent so that the bottom image could be visible.
For that I just need to add these line in my AppDelegate class’s didFinishLaunchingWithOptions function.
var imageForDefault = self.imageWithColor(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)) var imageForCompact = self.imageWithColor(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)) UINavigationBar.appearance().setBackgroundImage(imageForDefault, forBarMetrics: UIBarMetrics.Default) UINavigationBar.appearance().setBackgroundImage(imageForCompact, forBarMetrics: UIBarMetrics.Compact)
And add this imageWithColor function
func imageWithColor(color: UIColor) -> UIImage{ let rect:CGRect = CGRectMake(0, 0, 1, 1); UIGraphicsBeginImageContextWithOptions(rect.size, false, 0); color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() return image; }
So now the navigation bar is transparent but bottom shadow is still there. For that I just need another line of code.
UINavigationBar.appearance().shadowImage = self.imageWithColor(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0))
So the full code for this
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let imageForDefault = self.imageWithColor(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)) let imageForCompact = self.imageWithColor(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)) UINavigationBar.appearance().setBackgroundImage(gradientImage44, forBarMetrics: UIBarMetrics.Default) UINavigationBar.appearance().setBackgroundImage(gradientImage32, forBarMetrics: UIBarMetrics.Compact) UINavigationBar.appearance().shadowImage = self.imageWithColor(UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)) return true }
That is it.
You can download the code from Transparent Navigation Bar