Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get mouse location with SwiftUI?

Tags:

swift

swiftui

I am trying to make a popover display in SwiftUI. I already have this going, but is there a way to make my popoverView appear where I clicked? For this I think i need to get the mouse location. How do i do this?

like image 345
swift nub Avatar asked Aug 22 '19 21:08

swift nub


1 Answers

With help from SwiftUILab@twitter

struct ContentView: View {
    
    @State private var pt: CGPoint = .zero
    
    var body: some View {
        
        let myGesture = DragGesture(minimumDistance: 0, coordinateSpace: .global).onEnded({
            self.pt = $0.startLocation
        })
        
        // Spacers needed to make the VStack occupy the whole screen
        return VStack {
            
            Spacer()
            
            HStack {
                Spacer()
                Text("Tapped at: \(pt.x), \(pt.y)")
                Spacer()
            }
            
            Spacer()
            
        }
        .border(Color.green)
        .contentShape(Rectangle()) // Make the entire VStack tappabable, otherwise, only the areay with text generates a gesture
        .gesture(myGesture) // Add the gesture to the Vstack
    }
}
like image 130
swift nub Avatar answered Sep 20 '22 04:09

swift nub