Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Color Picker in SwiftUI
Written by Team Kodeco

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.
Use SwiftUI's ColorPicker view to display the system color picker.

Here’s what each part of the code does:

  • @State private var colorChoice = Color.white: State is a property wrapper in SwiftUI. It indicates that colorChoice is a source of truth in the application, and it should rerender the view when it changes. The initial color is set to white.
  • ColorPicker("Choose your color", selection: $colorChoice): The ColorPicker component presents a standard system color picker to the user. The string argument is the title of the color picker. The selection: parameter is a binding ($colorChoice) to the state variable colorChoice, which holds the selected color.
  • Rectangle().fill(colorChoice).frame(width: 100, height: 100): You’re creating a square that will be filled with the color chosen by the ColorPicker. This way, the user gets visual feedback of their color choice.
  • padding(): This adds some space around the components, making it look cleaner and more readable.

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!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.