如何使用SwiftUI获取鼠标位置?

8

我正在尝试在SwiftUI中制作一个弹出式视图(popover)。 我已经有了这个,但是有没有办法让我的popoverView出现在我点击的位置?为此,我认为需要获取鼠标位置。我该怎么做?

1个回答

8

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

2
但这不是最好的答案,我们必须点击才能获取位置,真正的答案应该在悬停时起作用!我们应该只需移动鼠标就能读取位置,而不需要移动和点击! - ios coder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接