如何在 SwiftUI 中以清晰/透明背景设置导航栏?

pro*_*ith 4 ios swift swiftui

我想弄清楚如何为自定义导航栏编写代码以显示清晰/透明的栏而不是“白色”栏。看这个截图:

这是我的代码:

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()
    
 }
}
Run Code Online (Sandbox Code Playgroud)

有人知道它有什么问题吗?

hig*_*ech 11

我试图在我的 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()

          }
    }
Run Code Online (Sandbox Code Playgroud)

我希望这对你有帮助。