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:
 
    
Here’s what each part of the code does:
- 
@State private var colorChoice = Color.white:Stateis a property wrapper in SwiftUI. It indicates thatcolorChoiceis 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): TheColorPickercomponent presents a standard system color picker to the user. The string argument is the title of the color picker. Theselection:parameter is a binding ($colorChoice) to the state variablecolorChoice, 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 theColorPicker. 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!