How it works
A ColorPicker is a control that lets people select a color from the system color interface, presenting a swatch that opens the platform's standard color panel or grid. Use it whenever your interface exposes a user-adjustable color — a stroke, a fill, a theme accent — and you want that selection to ride on a Color binding rather than a hand-built palette. Because it reads and writes a binding, the chosen color flows straight back into your view's state, keeping the picker and whatever it tints in sync.
Bind the selection to a Color with the title initializer
The common initializer takes a localized title string and a
selectionbinding of typeBinding<Color>. The title labels the control; the binding is the live channel through which the picker reports the chosen color. HereColorPicker("Stroke Color", selection: $strokeColor)labels the row "Stroke Color" and reads and writes the$strokeColorbinding.Back the binding with @State
ColorPickerneeds a mutable source of truth to mutate, so the boundColoris typically owned by a@Stateproperty. Declaring@State private var strokeColor = Color.bluegives the picker a starting value and a place to store each new selection; the leading$in$strokeColorprojects that state into theBinding<Color>the initializer expects.Drive other views from the same binding
Because the selection writes back through the binding, any view that reads the same property re-renders when the color changes. Passing
strokeColorto.fill(strokeColor)on theRoundedRectanglemeans the rectangle repaints the instant someone picks a new color in the picker, with no extra wiring.Reach for the opacity-aware or label-closure overloads
Beyond the title-string form,
ColorPickeroffers asupportsOpacityparameter to let people adjust alpha, and a trailing-closure overload that takes an arbitrary label view instead of a string. The example uses the simplest title form, but you can swap in those initializers when you need transparency control or a custom label.
ColorPicker("Stroke Color", selection: $strokeColor) to ColorPicker("Stroke Color", selection: $strokeColor, supportsOpacity: true) and watch the picker gain an opacity slider whose alpha shows through the rectangle's fill.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct ColorPickerDemo: View {
@State private var strokeColor = Color.blue
var body: some View {
VStack(spacing: 20) {
ColorPicker("Stroke Color", selection: $strokeColor)
RoundedRectangle(cornerRadius: 12)
.fill(strokeColor)
.frame(width: 120, height: 80)
}
.padding()
}
}