【问题标题】:How to make navigation bar transparent in iOS 10如何在 iOS 10 中使导航栏透明
【发布时间】:2016-06-24 18:40:17
【问题描述】:
我有以下代码使导航栏透明,但仍显示后退按钮,这适用于所有版本的 iOS,但它停止使用 iOS 10 测试版
navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
navigationBar.shadowImage = UIImage()
navigationBar.isTranslucent = true
iOS 10 在这方面有什么变化吗?
请注意,它不能使用 navigationBar.isHidden,因为这会导致导航栏后退按钮和标题等也消失。
【问题讨论】:
标签:
ios
swift
uinavigationbar
【解决方案1】:
我不知道 iOS 10 中发生了什么变化以阻止以前的代码工作,但为了修复它,我创建了一个透明图像(它只需要一个像素的尺寸)并使用以下代码制作导航栏透明(但仍显示返回导航按钮)。
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
【解决方案2】:
@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!
}
}
【解决方案3】:
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