Color Picker in SwiftUI 2.0 — TechXposer

Abdihakin Elmi
2 min readJan 7, 2021

Color picker provides a color well that shows the currently selected color and displays the larger system color picker that allows users to select a new color.

By default color picker supports colors with opacity. to disable opacity support, set the supportOpacity parameter to false. in this mode the color picker won’t show controls for adjusting the opacity of the selected color and strips out any opacity from any color.

you can use color picker by embedding it inside a view hierarchy and initializing it with a title string and a binding to a color.

in the color picker, you’ve different colors like

All right so let’s open up xCode and create new project. we are going to stick with the app template under the ios tap and let’s go and give this a name ColorPickerSwiftUi and make sure your interface and lifecycle is SwiftUi, as well as your language, is swift. go ahead and continue.

so now we are going to create a screen where we could go ahead and get this really nifty looking color picker and based on whatever we select the background color actually changes.
so the first thing we are going to do here in the Content View is toss in a navigation view that basically houses our actual views. so let’s create a ZStack so that we can it a nice navigation title and call it Color Picker

NavigationView {
ZStack {
Text("Hello World")
}.navigationTitle("Color Picker")
}

the next thing you want to do is bring in that row that says select color as well as the cool component.
when you initially saw it might have looked like a lot of work it is actually extremely simple since it is a built-in SwiftUi component literally called ColorPicker so if you open up the constructor here you’ll see a couple of different values you can bring in the one that you want is title and selection.

struct ContentView: View {
///State property
@State var backgroundColor = Color(.systemBackground)
var body: some View {
NavigationView {
ZStack {
/// changes the background when ever we change.
backgroundColor
///the title that is gonna show in the row.
ColorPicker("Select Color",
/// the property that hold the color once we select it
selection: $backgroundColor)
.padding()
}.navigationTitle("Color Picker")
}
}
}

Originally published at https://techxposer.net on January 7, 2021.

--

--