Part 5 Allowing a tap to set a value | Create the Color Picker with SwiftUI

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.

TOC

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()
    }
}
Display tapped coordinates
Display tapped coordinates

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.

Running in live preview on Xcode
Running in live preview on Xcode

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.

Create the Color Picker with SwiftUI

Let's share this post !

Author of this article

Akira Hayashiのアバター Akira Hayashi Representative, Software Engineer

I am an application developer loves programming. This blog is a tech blog, its articles are learning notes. In my work, I mainly focus on desktop and mobile application development, but I also write technical books and teach seminars. The websites of my work and books are here -> RK Kaihatsu.

TOC