Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a path selectable in swiftui

Tags:

ios

swift

swiftui

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. Line on screen

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.

like image 352
yawnobleix Avatar asked Jan 31 '26 07:01

yawnobleix


1 Answers

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.

enter image description here

like image 117
Visal Rajapakse Avatar answered Feb 02 '26 23:02

Visal Rajapakse



Donate For Us

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