透明的导航栏在设计界很受欢迎。您必须这样做只是时间问题。我们将在本文中探索不同的方法来做到这一点。
我将把这样做的方法分为两类。
- 在全局,我们将应用程序范围内的导航栏设置为透明。
- 在本地,我们仅将导航栏的一些实例设置为透明。
iOS 13 之前
您需要做三件事才能使导航栏透明。
# 精品教程推荐
- [《CSDN SwiftUI源码大全》](https://www.openswiftui.com/?gr_redirect=csdn-swiftui%e6%ba%90%e7%a0%81%e5%a4%a7%e5%85%a8)
- [《小专栏 SwiftUI教程》](https://www.openswiftui.com/?gr_redirect=%e5%b0%8f%e4%b8%93%e6%a0%8f-swiftui%e6%95%99%e7%a8%8b)
将背景图像设置为非零空图像 ( UIImage())。
将阴影图像设置为非零空图像 ( UIImage())。
设置isTranslucent为true。
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().isTranslucent = true
iOS 13 以上
在 iOS 13 中,这个过程变得更简单了,有了一个新UINavigationBarAppearance类,它是一个保留导航栏所有外观属性的对象。
只需要通过callconfigureWithTransparentBackground()方法进行透明后台配置即可。将条形外观对象配置为透明背景是一种方便的方法。
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
UINavigationBar.appearance().standardAppearance = appearance
iOS 13 之前的方式在 iOS 13 中仍然有效。不过,我建议您坚持使用其中一个UINavigationBarAppearance或旧的外观属性,不要将两者混合使用,因为它可能会覆盖另一个效果。
使导航栏实例透明
要为特定的导航栏实例应用透明导航栏,您需要重复我们在上一步中所做的过程,但将其设置在导航栏实例上而不是UINavigationBar.appearance().
iOS 13 之前
您可以在初始化UINavigationController实例时设置它,也可以在子视图控制器中设置它。
初始化时设置导航栏外观UINavigationController。
let nav = UINavigationController(rootViewController: ViewController())
nav.navigationBar.setBackgroundImage(UIImage(), for: .default)
nav.navigationBar.shadowImage = UIImage()
nav.navigationBar.isTranslucent = true
在子视图控制器中设置导航栏外观。
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
}
在视图控制器中设置导航栏外观与直接在导航栏创建时设置它的效果相同。导航栏将保持透明,直到其他视图控制器更改它。
iOS 13 以上
我们可以像在Pre iOS 13UINavigationBarAppearance方法中那样设置它,但这次我们改用它。
初始化时设置导航栏外观UINavigationController。
let nav = UINavigationController(rootViewController: ViewController())
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
nav.navigationBar.standardAppearance = appearance
在子视图控制器中设置导航栏外观。
override func viewDidLoad() {
super.viewDidLoad()
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
navigationController?.navigationBar.standardAppearance = appearance
}
精品教程推荐
-
加入我们一起学习SwiftUI
QQ:3365059189
SwiftUI技术交流QQ群:518696470
教程网站:www.openswiftui.com