iOS 10 如何让导航栏透明

How to make navigation bar transparent in iOS 10

我有以下代码使导航栏透明,但同时仍显示后退按钮,这适用于 iOS 的所有版本,但在 iOS 10 beta

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

这个区域的 iOS10 有什么变化吗?

注意不能使用 navigationBar.isHidden,因为这会导致导航栏后退按钮和标题等也消失。

我不知道 iOS10 中发生了什么变化以阻止以前的代码工作,但为了修复它我创建了一个透明图像(它只需要一个像素的尺寸)并使用以下代码使导航栏透明(但仍显示后退导航按钮)。

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

顺带一提,如果要改变导航栏的颜色,可以用同样的原理:

    let redPixel = UIImage(named: "RedPixel")
    navigationBar.setBackgroundImage(redPixel, for: UIBarMetrics.default)
    navigationBar.shadowImage = redPixel
    navigationBar.isTranslucent = false

@Essence提供的解决方案完美无缺!
这就是我用来通过代码创建 1px 透明图像的方法:

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!
  }
}

Swift 3.x

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.backgroundColor = .clear
self.navigationController?.navigationBar.isTranslucent = true