General Middleware

How to handle Dark Mode in Swift

Apple introduced a new mode called “Dark Mode” from iOS 13.0 onwards. Users can easily switch between the Light and the Dark Modes from Settings.

While building your apps, it is extremely important that you handle this mode change, otherwise, few of your app contents might not be visible or poorly visible in contrast to the background.

There are 3 ways you can handle this.

  1. You can select only one mode for your App from the info.plist. In this case, the app will not be affected at all by the user’s mode change. Just add the mode as “Light” or “Dark” against the “Appearance” in info.plist

2. If you want only few parts of your App to remain unaffected by the Mode Change, then, insert below code in your viewDidLoad() method for those ViewControllers, that should remain unchanged.

overrideUserInterfaceStyle = .light //or .dark

3. The last option is where you choose how the app will behave in case of Mode Changes. Note that you need to repeat the same code in the viewWillAppear and traitCollectionDidChange methods.

viewWillAppear will be called every time the view appears, and traitCollectionDidChange is to take care of the mode change while the app is already open in the background.

    override func viewWillAppear(_ animated: Bool) {
        let userInterfaceStyle = traitCollection.userInterfaceStyle
        if userInterfaceStyle == .light {
            //Update code to change background or tint colors here
        } else if userInterfaceStyle == .dark {
            //Update code to change background or tint colors here
        }
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        let userInterfaceStyle = traitCollection.userInterfaceStyle
        if userInterfaceStyle == .light {
            //Update code to change background or tint colors here
        } else if userInterfaceStyle == .dark {
            //Update code to change background or tint colors here
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *