73 - Create a Color Picker in SwiftUI

Imagine you’re developing a drawing app, and you need to give your users the ability to choose their own custom colors. SwiftUI has a built-in solution that you can quickly and easily plug into your app to solve this problem: the ColorPicker view.

Here’s a simple example of a color picker in SwiftUI:

struct ContentView: View {
  @State private var colorChoice = Color.white

  var body: some View {
    VStack {
      ColorPicker("Choose your color", selection: $colorChoice)
        .padding()

      Text("You chose:")
        .font(.title)

      Rectangle()
        .fill(colorChoice)
        .frame(width: 100, height: 100)
        .padding()
    }
  }
}

Your preview should look like this:

Use SwiftUI's ColorPicker view to display the system color picker.

Here’s what each part of the code does:

And there you have it. By using SwiftUI’s built-in ColorPicker view, you can provide an intuitive and familiar interface for your users to pick colors, making your apps more customizable and enjoyable. Happy coding!