Color Pickers

Last updated on 19 Oct 2024.

Written by Jia Chen.

Color Pickers

Last updated on 19 Oct 2024.

Written by Jia Chen.

Color Pickers

Last updated on 19 Oct 2024.

Written by Jia Chen.

Scroll Down

On this page

Video

On this page

Creating a Color Picker

To create a Color Picker, you will need to supply it with a Label that describes the purpose of your color picker and a Binding color.

In the following example, a ZStack is used to display the selected Color as the background color.

struct ContentView: View {
    
    @State private var color: Color = .red
    
    var body: some View {
        ZStack {
            color
            ColorPicker("Background Color", selection: $color)
        }
    }
}

When using Swift Playgrounds on Mac, the color picker appears as a native macOS color picker in a rectangular box with a separate window to select the color.

Labels

Text Labels

To create a Color Picker, you will need a State variable of the type Color.

@State private var selectedColor = Color.blue
ColorPicker("Background Color", selection: $color)

Custom Labels

You can also pass in a custom label to go along with color picker.

ColorPicker(selection: $color) {
    Image(systemName: "person.and.background.dotted")
}

Supporting Opacity

By default, Color Pickers support opacity. You can disable this behavior with the supportsOpacity parameter.

ColorPicker("Background Color", selection: $color, supportsOpacity: true)
ColorPicker(selection: $color, supportsOpacity: false) {
    Image(systemName: "person.and.background.dotted")
}

Hiding Labels

If you prefer not to have the label in your color picker, you can use the labelsHidden modifier to remove it.

It is best practice to still use an appropriate text label for your color picker, even if it might not be visible. This can help with assistive technologies like VoiceOver.

ColorPicker("Background Color", selection: $color, supportsOpacity: true)
    .labelsHidden()

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.