This is a series of articles on creating a color picker in SwiftUI. In this article, we will implement the code to allow tapping on the gradient view of the color picker to set RGB values.
To support tap gestures in SwiftUI
To support tap gestures in SwiftUI, use the onTapGesture
modifier. onTapGesture
modifier has a variation with different arguments. iOS 16, iPadOS 16, macOS 13, and watchOS 9.0 have added a modifier that passes the tapped coordinates.
For example, the following code displays the tapped coordinates in the red view on a label.
struct ContentView: View {
@State private var tappedPoint = CGPoint()
var body: some View {
VStack {
GeometryReader { geometry in
Path { path in
path.addRect(CGRect(x: 0, y: 0, width: geometry.size.width, height: geometry.size.height))
}
.fill(.red)
}
.onTapGesture { point in
tappedPoint = point
}
Text("Tapped: \(tappedPoint.x), \(tappedPoint.y)")
}
.padding()
}
}

Calculate current value from coordinates
Implement the code to calculate the current value from the coordinates. The left edge of the PickerGradationView is 0.0 and the right edge is 1.0 , so dividing the X coordinate of the tapped coordinate by the width of the PickerGradationView will give the current value of the channel as it is.
The code for the Red channel is as follows.
PickerGradationView(startColor: redStartColor, endColor: redEndColor)
.frame(height: 100)
.background {
GeometryReader { geometry in
Path { path in
DispatchQueue.main.async {
if geometry.size != redGradationViewSize {
redGradationViewSize = geometry.size
}
}
}
}
}
.onTapGesture { point in
channelValue.red = point.x / redGradationViewSize.width
}
What we have added is the onTapGesture
modifier, and the code for the Green and Blue channels will be the same.

Download the sample code
Click here to download the code created for this article.
Serialized Articles
This article is part of a series of articles titled “Create the Color Picker with SwiftUI”. Other articles in the series are here.