如何在 macOS SwiftUI 视图中读取并访问鼠标光标位置?

use*_*ser 3 swift swiftui

这是我非常简单的入门项目,正如您在问题标题中看到的那样,我想在 macOS SwiftUI 中的视图上悬停或移动时读取鼠标光标的位置。对于入门项目,我使用了手势!手势的问题在于,用户应该进行某种点击或拖动,这会触发手势,但我想获得手势的所有好处,而不必进行点击或拖动,我该怎么做?

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 })

    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 5

尝试使用下面的代码,请注意,它将提供屏幕内当前的整体鼠标位置,而不仅仅是窗口内。但是,您可以使用.onHover方法 来了解鼠标何时位于视图上。

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
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

}