如何使用 SwiftUI 获取鼠标位置? [英] How to get mouse location with SwiftUI?

查看:42
本文介绍了如何使用 SwiftUI 获取鼠标位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 SwiftUI 中进行弹出显示.我已经有了这个,但是有没有办法让我的 popoverView 出现在我点击的地方?为此,我想我需要获取鼠标位置.我该怎么做?

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?

推荐答案

SwiftUILab@twitter 的帮助下>

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()
            Text("Tapped at: \(pt.x), \(pt.y)")
            Spacer()
            HStack { 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
    }
}

这篇关于如何使用 SwiftUI 获取鼠标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆