Home > Net >  Change safe area color in dark mode
Change safe area color in dark mode

Time:08-26

I am using this code:

window?.safeAreaLayoutGuide.owningView?.backgroundColor = 
        UIColor(red:243.0/255.0, green:243.0/255.0, blue:243.0/255.0, alpha:1.0)

in SceneDelegate for change safe area color. And I want to change color of safe area for dark mode.

How can I do?

CodePudding user response:

The best way to do this is to set up a Color Asset which has both light mode and dark mode variants included. This is simple to do, and once you have it set up, light/dark mode transitions will be handled automatically.

First, select your Assets.xcassets file, and right click anywhere within the left hand sidebar (under where it says "AccentColor" and "AppIcon"). This will open a popup menu; from there select "New Color Set." Now you should see a square named "Color" in the sidebar, and two squares labeled "Any Appearance" and "Dark" in the middle of the screen.

Next, click on one of those two squares. In the right hand sidebar, a color selector will pop up (with red, green, blue and opacity sliders, and the option to open the color selector panel). You can use these to set the RGB values you want for both light mode (the "Any Appearance" square) and dark mode.

Now that you've specified the color values, you still need a way to reference your new Color Asset from your code. This can be done with the UIColor(named: String) initializer. In Assets.xcassets, change the name from Color to whatever you want it to be called (I'll use "SafeAreaColor" as an example). Now, somewhere in your program (I usually do this in the Constants file) you should initialize the color:

let safeAreaColor = UIColor(named: "SafeAreaColor")

The last step is to incorporate this custom color into your existing code:

window?.safeAreaLayoutGuide.owningView?.backgroundColor = safeAreaColor

Now, your safe area should automatically change colors when the device shifts between Light and Dark mode.

  • Related