I want to be able to draw a line in swiftui where only the line is selectable, this works fine for vertical and horizontal lines but when the line is on an angle the hit area
My code for drawing a line from one corner of the frame to the other:
struct AngleLine: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: rect.minX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
}
}
}
Then in my view I put this into a button
struct LineSelector: View {
var lineWidth : CGFloat
let dash : [CGFloat] = [6, 3]
let size : CGFloat
var body: some View {
VStack{
Button(action: {
print("Hello")
}) {
AngleLine().stroke(style: StrokeStyle(lineWidth: lineWidth, dash: [6, 3])).fill(Color.red)
}
}
}
}
See this image for the result.

The issue is that now the frame fills the entire screen and everything becomes the button, when the goal is to only have the line be a button, not the entire frame.
Instead of wrapping your AngleLine() with a Button you can add a .onTapGesture{} into the Shape object. See the following code
AngleLine().stroke(style: StrokeStyle(lineWidth: lineWidth, dash: [6, 3])).fill(Color.red)
.onTapGesture { // <-- Adding the tap gesture
print("Hello")
}
This will prevent the entire frame of the shape from acting as a button. See the output of the above code, below.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With