Home > AI > IOS > SwiftUI >

customize navigationbar background color

Example 1: Global which is undesired

struct ExperienceView: View {
  
    init() {
        UINavigationBar.appearance().barTintColor = #colorLiteral(red: 0.1764705882, green: 0.2196078431, blue: 0.3098039216, alpha: 1)
        UINavigationBar.appearance().isTranslucent = false
        UINavigationBar.appearance().shadowImage = UIImage()
        
    }
}

Example 2: Local

We need to use UIViewControllerRepresentabe.

struct UINavigationConfiguration: UIViewControllerRepresentable {
    var config: (UINavigationController) -> Void = {_ in }
    
    func makeUIViewController(context: Context) -> UIViewController {
        let controller = UIViewController()
        DispatchQueue.main.async {
            if let nc = controller.navigationController {
                self.config(nc)
            }
        }
        return controller
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        if let nc = uiViewController.navigationController {
            self.config(nc)
        }
    }

}

ContentView.swift

struct ContentView: View {
 
    var body: some View {
        TabView {
            FirstView()
                .tabItem {
                    VStack{
                        Image(systemName: "pencil")
                        Text("first")
                    }
                }
            
            SecondView()
                .tabItem {
                    VStack{
                        Image(systemName: "pencil")
                        Text("second")
                    }
                }
        }
    }
}

FirstView.swift

struct FirstView: View {
    var body: some View {
        NavigationView {
            NavigationLink(
                destination: FirstDetailView(),
                label: {
                    Text("FirstView")
                })
                .navigationBarTitle("First", displayMode: .inline)
                .background(UINavigationConfiguration { nc in
                    nc.navigationBar.barTintColor = .blue
                    nc.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
                })
        }
    }
}

SecondView.swift

struct SecondView: View {
    var body: some View {
        NavigationView {
            NavigationLink(
                destination: SecondDetailView(),
                label: {
                    Text("SecondView")
                })
                .navigationBarTitle("Second", displayMode: .inline)
                .background(UINavigationConfiguration { nc in
                    nc.navigationBar.barTintColor = .orange
                    nc.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
                })
        }
    }
}

Leave a Reply