[英]How to set a navigation bar in clear / transparent background in SwiftUI?
I am trying to figure out how to write a code for a custom navigation bar to display clear / transparent bar not "white" bar.我试图弄清楚如何为自定义导航栏编写代码以显示清晰/透明栏而不是“白色”栏。 See this screenshot: https://pasteboard.co/IBYJDtx.png
看到这个截图: https://pasteboard.co/IBYJDtx.png
Here is my code:这是我的代码:
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()
}
}
Does anybody know what is wrong with it?有人知道它有什么问题吗? Any suggestion appreciated.
任何建议表示赞赏。
I tried to run your code on my Xcode.我试图在我的 Xcode 上运行您的代码。 I received the same results like yours.
我收到了和你一样的结果。 I found a good solution to fix this issue.
我找到了一个很好的解决方案来解决这个问题。 You just need to add a few lines of code into your
init()
.您只需在
init()
中添加几行代码。 Here is the solution:这是解决方案:
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()
}
}
I hope that helps you.我希望这对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.