• SwiftUI Dark Mode — the Easiest Way
  • By Mahmud Ahsan
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: zhuzilin
  • Proofreader: KeepmovingLjZY, Zenblo, LSvih

SwiftUI Dark Mode — the easiest way

When I started developing my iOS apps with SwiftUI this year, I decided to support both light and dark modes. In this tutorial, I will teach you how to implement the light and shade mode for the user interface in SwiftUI iOS applications.

1. Create a new project

Let’s create a new XCode project and choose to use SwiftUI to construct the interface (Inference).

2. Create a user interface

Replace all the code in the contentView.swift file with the following code, which will create a page with two card views.

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            CardView(title: "Mark")
            CardView(title: "Bill")
            Spacer()}}}struct CardView: View {
    let title: String
    
    var body: some View {
        VStack {
            Text(title)
                .font(.headline)
                .padding(40)
        }
        .frame(maxWidth: .infinity)
        .background(Color.gray)
        .cornerRadius(10)
        .padding(.horizontal, 10)
        .padding(.bottom, 10)}}struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()}}Copy the code

Run or preview the app and you should see the user interface as shown below:

3. Create colors

Now select Assets.xcassets in XCode

  • Create a new color set and name it foregroundTitle1
  • chooseAny Appearance, in the color property, put theInput MethodSet to8-bit HexadecimalAnd theHexA value for#0974B8
  • Then selectDark AppearanceAnd set to#E0F2FD

In simple terms, for foregroundTitle1, you create two different color assets for the light and dark modes.

Next, follow the same steps to create another set of colors for the background colors of the card.

  • The name of the color set is background1
  • forAny AppearanceSet the 8-bit hexadecimal value#C9CED9.Dark AppearanceSet to# 333333

You have now created two sets of foreground and background colors.

4. Create color extensions

Create a new file called extensions.swift and write the following code:

import SwiftUI

/// Color
extension Color {
    static func CardForeground(a) -> Color {
        Color("foregroundTitle1")}static func CardBackground(a) -> Color {
        Color("background1")}}Copy the code

Using extensions is a good way to add functionality to existing classes. Here you create two static methods that each return an instance of Color to value from Color Assets. This way, you can apply the specified color set simply by using the name of the color you created in Color Asset.

5. Update foreground and background colors

Replace all the code in the contentView.swift file again with the following code.

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            CardView(title: "Mark", colorForeground: Color.CardForeground(), colorBackground: Color.CardBackground())
            CardView(title: "Bill", colorForeground: Color.CardForeground(), colorBackground: Color.CardBackground())
            Spacer()}}}struct CardView: View {
    let title: String
    let colorForeground: Color
    let colorBackground: Color
    
    var body: some View {
        VStack {
            Text(title)
                .font(.headline)
                .padding(40)
        }
        .frame(maxWidth: .infinity)
        .foregroundColor(colorForeground)
        .background(colorBackground)
        .cornerRadius(10)
        .padding(.horizontal, 10)
        .padding(.bottom, 10)}}struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
                .colorScheme(.light)
        }
        
        Group {
            ContentView()
                .colorScheme(.dark)
        }
    }
}
Copy the code
  • 15 and 16Update by adding 2 color referencesCardViewview
  • 25, 26Plus what I just addedforegroundColorbackgroundColor
  • Line 6, 7Pass the color reference to the one you created in the extensionCardView
  • 35-43– by providingcolorSchemeThe incoming.light.darkYou have viewed two groups of previews

You will see the following in the preview file.

When running the app, change the Settings on your iPhone or iPad to bright or dark mode, and you’ll see the app automatically display the colors you’ve chosen for each mode.

The source code

conclusion

This is just a simple way to create a chiaroscuro mode in iOS apps using SwiftUI. If you want to develop applications that support both color modes, you should either support them from the start or create extensions to support color extensions.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.