我想弄清楚如何为自定义导航栏编写代码以显示清晰/透明栏而不是“白色”栏。看这个截图:
这是我的代码:
import SwiftUI
struct ContentView: View {
init() {
UINavigationBar.appearance().tintColor = .clear
UINavigationBar.appearance().backgroundColor = .clear
}
var body: some View {
NavigationView {
ZStack {
Color(.lightGray).edgesIgnoringSafeArea(.all)
VStack() {
Spacer()
Text("Hello").foregroundColor(.white)
Spacer()
}
}
.navigationBarTitle(Text("First View"), displayMode: .inline)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
有人知道它有什么问题吗?
最佳答案
我试图在我的 Xcode 上运行您的代码。我收到了和你一样的结果。我找到了解决此问题的好方法。您只需在 init()
中添加几行代码。这是解决方案:
import SwiftUI
struct ContentView: View {
init() {
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: UIBarMetrics.default)
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().isTranslucent = true
UINavigationBar.appearance().tintColor = .clear
UINavigationBar.appearance().backgroundColor = .clear
}
var body: some View {
NavigationView {
ZStack {
Color(.lightGray).edgesIgnoringSafeArea(.all)
VStack() {
Spacer()
Text("Hello").foregroundColor(.white)
Spacer()
}
}
.navigationBarTitle(Text("First View"), displayMode: .inline)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
希望对你有帮助。
关于ios - 如何在 SwiftUI 中设置清晰/透明背景的导航栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58383318/