Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a navigation bar in clear / transparent background in SwiftUI?

Tags:

ios

swift

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:

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?

like image 933
prosmith Avatar asked Dec 18 '22 15:12

prosmith


1 Answers

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.

like image 109
hightech Avatar answered May 10 '23 13:05

hightech