swiftPunk
swiftPunk

Reputation: 1

How can I read and get access to mouse cursor location in a view of macOS SwiftUI?

Here is my very simple and starter project, as you can see in question title I want to read the mouse cursor location when it hover or move on my view in macOS SwiftUI. For starter project I used gesture! The issue with gesture is there that the user should do some kind of tap or drag and that would trigger the gesture, but I want to get all benefit of gesture without having to make a tap or drag, how can I do this?

struct ContentView: View {
    
    @State private var location: CGPoint = .zero
    
    var body: some View {

        return VStack {
            
            Spacer()
            
            HStack {
                Spacer()
                Text("location is: ( \(location.x), \(location.y))").bold()
                Spacer()
            }

            Spacer()
 
        }
        .background(Color.yellow)
        .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local)
                    .onEnded { value in location = value.location })

    }
}

enter image description here

Upvotes: 3

Views: 3769

Answers (1)

Francisco D. Hurtado
Francisco D. Hurtado

Reputation: 129

try using the code below, note that it will provide the current overall mouse position inside the screen, not only inside the window. However you can use the method .onHover in order to know when the mouse is over a view.

struct ContentView: View {
var mouseLocation: NSPoint { NSEvent.mouseLocation }
@State var isOverContentView: Bool = false
var body: some View {
    ZStack{
        //Place your view
        Image(systemName: "applelogo")
            .resizable()
            .scaledToFill()
            .frame(width: 200, height: 200)
            .onHover{ on in
                isOverContentView = on
            }
    }
    .frame(width: 600, height: 600)
    .onAppear(perform: {
        NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved]) {
            print("\(isOverContentView ? "Mouse inside ContentView" : "Not inside Content View") x: \(self.mouseLocation.x) y: \(self.mouseLocation.y)")
            return $0
        }
    })
}

}

Upvotes: 6

Related Questions