swiftswiftui

How to change app tint color (New SwiftUI life cycle app)?


What is the best way to change app tint color in a SwiftUI app?

It is powered by the new SwiftUI lifecycle so I do not have the option to perform self.?tintColor

Tried searching here but didn't find any way to do it in a SwiftUI lifecycle app.


Solution

  • In the SceneDelegate.swift where you create the window for your app you can set the tint color globally using the tintColor property of UIWindow

    let contentView = ContentView()
    
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView)
        self.window = window
    
        self.window?.tintColor = UIColor.red // Or any other color you want
        window.makeKeyAndVisible()
    }
    

    Edit
    After seeing that you want it for the new SwiftUI, you can create new EnvironmentKeys:

    private struct TintKey: EnvironmentKey {
        static let defaultValue: Color = Color.blue
    }
    
    extension EnvironmentValues {
        var tintColor: Color {
            get { self[TintKey.self] }
            set { self[TintKey.self] = newValue }
        }
    }
       
    @main
    struct YourApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView().environment(\.tintColor, Color.red)
            }
        }
    }
    

    Then in your views you would use it like this:

    struct ContentView: View {
        @Environment(\.tintColor) var tintColor
        
        var body: some View {
            VStack {
                Text("Hello, world!")
                    .padding()
                Button(action: {}, label: {
                    Text("Button")
                })
            }.accentColor(tintColor)       
        }
    }