Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make SwiftUI navigation bar transparent

I'm searching for a way to make the NavigationBar transparent. My NavigationView is in the root view in ContentView which contains a TabView.

import SwiftUI

struct ContentView: View {
var body: some View {
    TabView {
       HomeView().tabItem {
            Image(systemName: "house.fill")
            Text("Home")
        }.tag(1)
        NavigationView {
        SearchView()
            }

        .tabItem {
            Image(systemName: "magnifyingglass")
            Text("Search")
        }.tag(2)
}

The NavigationView Bar displays even after adding the following modifier in the root view.

init() { 
UINavigationBar.appearance().backgroundColor = .clear
UINavigationBar.appearance().isHidden = false

}

Below is the child view in which I'm trying to hide the navigationbar background.

import SwiftUI

struct FacilityView: View {


var perks = "Badge_NoPerks"
var image = "Image_Course6"
var courseName = "Course"

var body: some View {
    VStack {
        HStack {
            Image(image)
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: UIScreen.main.bounds.width, height: 260)
        }
        VStack(alignment: .leading) {
            HStack {
                Image(perks)
            }
            HStack {
                Text(courseName)
                Spacer()
            }
        }
        .padding(.horizontal)
        Spacer()
    }.padding(.horizontal)
       .edgesIgnoringSafeArea(.top)
      .navigationBarTitle("Facility Details")


}

}

like image 889
Jason Tremain Avatar asked Aug 22 '19 20:08

Jason Tremain


2 Answers

Try adding these to your init() modifiers:

UINavigationBar.appearance().barTintColor = .clear
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)

It worked for me in Xcode 11.2.1, iOS 13.2

like image 86
Cliff Avatar answered Sep 19 '22 09:09

Cliff


You can use this extension to UINavigationBar to toggle between transparent and default appearance.

extension UINavigationBar {
    static func changeAppearance(clear: Bool) {
        let appearance = UINavigationBarAppearance()
        
        if clear {
            appearance.configureWithTransparentBackground()
        } else {
            appearance.configureWithDefaultBackground()
        }
        
        UINavigationBar.appearance().standardAppearance = appearance
        UINavigationBar.appearance().compactAppearance = appearance
        UINavigationBar.appearance().scrollEdgeAppearance = appearance
    }
}

and in your view structs:

struct ContentView: View {
    init() {
        UINavigationBar.changeAppearance(clear: true)
    }
    var body: some View {
        NavigationView {
            ...
        }
    }
}
like image 31
alionthego Avatar answered Sep 22 '22 09:09

alionthego