【问题标题】:How to get mouse location with SwiftUI?如何使用 SwiftUI 获取鼠标位置?
【发布时间】:2019-08-22 21:41:38
【问题描述】:

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

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

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

    【讨论】:

    • 但这不是最好的答案,我们必须点击才能获得位置,真正的答案应该在悬停时起作用!我们应该能够通过移动鼠标而不是移动和点击来读取位置!
    猜你喜欢
    • 1970-01-01
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多