Skip to main content

How to let users select a color with ColorPicker

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to let users select a color with ColorPicker 관련

SwiftUI by Example

Back to Home

How to let users select a color with ColorPicker | SwiftUI by Example

How to let users select a color with ColorPicker

Updated for Xcode 15

SwiftUI has a native ColorPicker control that allows the user to select a color. To use it, first create a Color property that can be changed using @State or similar, then

struct ContentView: View {
    @State private var bgColor = Color.red

    var body: some View {
        VStack {
            ColorPicker("Set the background color", selection: $bgColor)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(bgColor)
    }
}

Download this as an Xcode projectopen in new window

The words “Set the background color” and a rainbow colored ring, below which is a grid style color picker with an opacity slider.
The words “Set the background color” and a rainbow colored ring, below which is a grid style color picker with an opacity slider.

By default ColorPicker supports opacity in the color selection, but you can disable that with a slightly different initializer:

struct ContentView: View {
    @State private var bgColor = Color.red

    var body: some View {
        VStack {
            ColorPicker("Set the background color", selection: $bgColor, supportsOpacity: false)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(bgColor)
    }
}

Download this as an Xcode projectopen in new window

The words “Set the background color” and a rainbow colored ring, below which is a grid style color picker without an opacity slider.
The words “Set the background color” and a rainbow colored ring, below which is a grid style color picker without an opacity slider.
Similar solutions…
How to let users select pictures using PhotosPicker | SwiftUI by Example

How to let users select pictures using PhotosPicker
How to let users select text | SwiftUI by Example

How to let users select text
How to let the user select multiple dates | SwiftUI by Example

How to let the user select multiple dates
How to let users import videos using PhotosPicker | SwiftUI by Example

How to let users import videos using PhotosPicker
How to let users share content using the system share sheet | SwiftUI by Example

How to let users share content using the system share sheet

이찬희 (MarkiiimarK)
Never Stop Learning.