Search code examples
swiftuisfsafariviewcontroller

SFSafariViewController - How to change the color of the address bar and tab menu


How to change the color of the address bar and tab menu in SwiftUi 3.0 using SFSafariViewController. I've tried various things, but that colour doesn't render itself in the simulator.

ContentView

        import SwiftUI
    import SafariServices
    
    struct ContentView: View {
        
        @State private var showSafari: Bool = false
        @State var animate = false
        @State var endSplash = false
        @State var vc = SFSafariViewWrapper(url: URL(string: "https://dc-levo.pewag40.com/login")!)
        
        var body: some View {
            ZStack {
                ZStack {
                    Color("Background")
                        .ignoresSafeArea(edges: .all)
                    
                    Image("splash")
                        .renderingMode(.original)
                        .aspectRatio(contentMode: .fit)
                        .padding(.all)
                    
                    
                }//zstack
                .ignoresSafeArea(edges: .all)
                
            }//zstack
            .ignoresSafeArea(edges: .all)
            .onAppear(perform: {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    self.showSafari = true
                }
            })
            .fullScreenCover(isPresented: $showSafari, content: {
                vc
            })
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }

How do I modify the code now to display a different color in Safari Web View? The color refers to the color of the address bar and the color of the tab bar located at the bottom of the display.


Solution

  • You can use preferredControlTintColor and/or preferredControlTintColor depending on your needs

    struct SFSafariViewWrapper: UIViewControllerRepresentable {
        let url: URL
    
        func makeUIViewController(context: UIViewControllerRepresentableContext<Self>) -> SFSafariViewController {
            let sfVC =  SFSafariViewController(url: url)
            sfVC.preferredBarTintColor = .blue // set color to tint the background of the navigation bar and the toolbar.
            sfVC.preferredControlTintColor = .yellow // set the color to tint the control buttons on the navigation bar and the toolbar.
            return sfVC
        }
    
        func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<SFSafariViewWrapper>) {
            return
        }
    }