Skip to content

ColorPicker in SwiftUI

In this SwiftUI tutorial, we will explore the powerful ColorPicker component, which allows users to select colors within your app. We’ll create a “Dynamic Theme Editor” that lets users customize the look of a sample note-taking app. This will not only introduce you to the basic functionality of ColorPicker but also its integration with real-world app features.

  1. ColorPicker: This component lets users choose a color. By binding it to state variables (backgroundColor and textColor), any changes made by the user are immediately reflected in the app’s UI.
  2. Customization Options: While ColorPicker supports opacity by default, you can disable it to simplify the color selection process.
import SwiftUI

struct ThemeEditorView: View {
  
@State private var backgroundColor = Color(.systemBackground) 
    @State private var textColor = Color.primary 

    var body: some View {

            Form {
             
                Section(header: Text("Customize Your Theme")) {
                    
                    ColorPicker("Background Color", selection: $backgroundColor, supportsOpacity: true)
                        .padding()
                    
                    ColorPicker("Text Color", selection: $textColor, supportsOpacity: false)
                        .padding()
                    
                }
            }.scrollContentBackground(.hidden)
            .background(backgroundColor)
            .foregroundColor(textColor)

    }

}
Back To Top