Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make navigation bar transparent in iOS 10

I have the following code to make the navigation bar transparent but while still displaying the back button, this works on all versions of iOS but its stopped working with the iOS 10 beta

    navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    navigationBar.shadowImage = UIImage()
    navigationBar.isTranslucent = true

Has something changed with iOS 10 in this area?

Note its not possible to use navigationBar.isHidden as this would result in the navigation bar back button and title etc. disappearing also.

like image 853
Gruntcakes Avatar asked Jun 24 '16 18:06

Gruntcakes


2 Answers

I don't know what has changed in iOS 10 to stop the previous code from working, but to fix it I created a transparent image (it only needs to be one pixel in dimension) and used the following code to make the navigation bar transparent (but still showing the back navigation button).

    let transparentPixel = UIImage(named: "TransparentPixel")
    navigationBar.setBackgroundImage(transparentPixel, for: UIBarMetrics.default)
    navigationBar.shadowImage = transparentPixel
    navigationBar.backgroundColor = UIColor.clear()
    navigationBar.isTranslucent = true

Incidentally, if you want to change the color of the navigation bar, you can use the same principle:

    let redPixel = UIImage(named: "RedPixel")
    navigationBar.setBackgroundImage(redPixel, for: UIBarMetrics.default)
    navigationBar.shadowImage = redPixel
    navigationBar.isTranslucent = false
like image 70
Gruntcakes Avatar answered Nov 04 '22 07:11

Gruntcakes


The solution @Essence provided works perfectly!
This is what I am using even to create the 1px transparent image by code:

class MainClass: UIViewController {

  let transparentPixel = UIImage.imageWithColor(color: UIColor.clear)

  override func viewWillAppear(_ animated: Bool) {
    drawCustomNavigationBar()
  }

  func drawCustomNavigationBar() {
    let nav = (self.navigationController?.navigationBar)!
    nav.setBackgroundImage(transparentPixel, for: UIBarMetrics.default)
    nav.shadowImage = transparentPixel
    nav.isTranslucent = true
  }
}

extension UIImage {
  class func imageWithColor(color: UIColor) -> UIImage {
    let rect = CGRect(origin: CGPoint(x: 0, y:0), size: CGSize(width: 1, height: 1))
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()!

    context.setFillColor(color.cgColor)
    context.fill(rect)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image!
  }
}
like image 40
DanielZanchi Avatar answered Nov 04 '22 06:11

DanielZanchi