简体   繁体   中英

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

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. 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() . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM