How to change tintColor of whole app? SwiftUI

后端 未结 2 1466
独厮守ぢ
独厮守ぢ 2020-12-18 11:33

So, I am supporting three themes in my app, each with different tintColors. I\'m using @EnvironmetObject to track changes. However, I can\'t use it on SceneDelegate.swift fi

相关标签:
2条回答
  • 2020-12-18 12:07

    You can achieve it by calling

    UIView.appearance(whenContainedInInstancesOf: [UIAlertController.self]).tintColor = .red
    

    in willConnectTo method of SceneDelegate

    0 讨论(0)
  • 2020-12-18 12:11

    Update: posted this demo on GitHub - DemoWindowTint

    The below demo is created on setting window's tintColor (which is inherited by all subviews) using the approach provided in How to access own window within SwiftUI view?.

    In demo I used NavigationView with couple of NavigationLinks and Button showing Alert.

    demo

    Tested with following

    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
    
    
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
            if let windowScene = scene as? UIWindowScene {
                let window = UIWindow(windowScene: windowScene)
    
                let contentView = ContentView()
                    .environment(\.hostingWindow, { [weak window] in
                        return window })
    
                window.rootViewController = UIHostingController(rootView: contentView)
    
                self.window = window
        ...
    
    struct ContentView: View {
        @Environment(\.hostingWindow) var hostingWindow
       ... // body can be any
    
        .onAppear {
                // can be loaded from UserDefaults here, and later changed on any action
                self.hostingWindow()?.tintColor = UIColor.red
        }
    
    0 讨论(0)
提交回复
热议问题