我试图弄清楚如何为自定义导航栏编写代码,以显示透明/透明栏而不是“白色”栏。看这个截图: https://pasteboard.co/IBYJDtx.png
这是我的代码:
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()
}
}
有人知道这是怎么回事吗?任何建议表示赞赏。
答案 0 :(得分:1)
我试图在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()
}
}
希望对您有所帮助。