How to let users select a color with ColorPicker
About 2 min
How to let users select a color with ColorPicker 관련
SwiftUI by Example
Back to Home
How to let users select a color with ColorPicker | SwiftUI by Example
How to let users select a color with ColorPicker
Updated for Xcode 15
SwiftUI has a native ColorPicker
control that allows the user to select a color. To use it, first create a Color
property that can be changed using @State
or similar, then
struct ContentView: View {
@State private var bgColor = Color.red
var body: some View {
VStack {
ColorPicker("Set the background color", selection: $bgColor)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(bgColor)
}
}
![The words “Set the background color” and a rainbow colored ring, below which is a grid style color picker with an opacity slider.](https://hackingwithswift.com/img/books/quick-start/swiftui/how-to-let-users-select-a-color-with-colorpicker-1~dark.png)
By default ColorPicker
supports opacity in the color selection, but you can disable that with a slightly different initializer:
struct ContentView: View {
@State private var bgColor = Color.red
var body: some View {
VStack {
ColorPicker("Set the background color", selection: $bgColor, supportsOpacity: false)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(bgColor)
}
}
![The words “Set the background color” and a rainbow colored ring, below which is a grid style color picker without an opacity slider.](https://hackingwithswift.com/img/books/quick-start/swiftui/how-to-let-users-select-a-color-with-colorpicker-2~dark.png)
Similar solutions…
How to let users select pictures using PhotosPicker | SwiftUI by Example
How to let users select pictures using PhotosPicker
How to let users select text | SwiftUI by Example
How to let users select text
How to let the user select multiple dates | SwiftUI by Example
How to let the user select multiple dates
How to let users import videos using PhotosPicker | SwiftUI by Example
How to let users import videos using PhotosPicker
How to let users share content using the system share sheet | SwiftUI by Example
How to let users share content using the system share sheet