【发布时间】:2021-09-19 09:14:48
【问题描述】:
在 iPad 上,我正在尝试构建一个简单的应用程序,该应用程序连续 跟踪指针在屏幕上移动时的坐标(通过外部鼠标/触控板)。基本上类似于 JavaScript example @ 4:13 的内容,除了 iPad 上的 SwiftUI 视图。
MacOS 有 NSEvent.mouseLocation,但似乎没有 iPadOS 对应物。我在网上遇到的每个资源都必须将坐标与手势(旋转、捏合、拖动、单击等)相关联,而无法响应 only 光标移动。这让我相信纯指针移动的解决方案可能独立于手势协议。
从SO post 修改代码后,我能够走到一半。我下面的代码显示更新的鼠标坐标只要指针正在拖动(即,至少按下一个按钮)。
import SwiftUI
struct ContentView: View {
@State private var pt = CGPoint()
@State private var txt = "init"
var body: some View {
let myGesture = DragGesture(
minimumDistance: 0,
coordinateSpace: .local
)
.onChanged {
self.pt = $0.location
self.txt = "x: \(self.pt.x), y: \(self.pt.y)"
}
// Spacers needed to make the VStack occupy the whole screen
return VStack {
Spacer()
Text(self.txt)
Spacer()
}
.frame(width: 1000, height: 1000)
.border(Color.green)
.contentShape(Rectangle()) // Make the entire VStack tappabable, otherwise, only the area with text generates a gesture
.gesture(myGesture) // Add the gesture to the Vstack
}
}
现在,如何在不需要拖动的情况下实现这种效果?如果无法实现纯 Swift 解决方案,是否有办法在 Objective-C 的帮助下做到这一点?
谢谢
编辑:
【问题讨论】:
-
如果没有手指向下,它应该如何跟踪 touch?
-
抱歉,我不想在触摸事件之后获取坐标。当指针在屏幕上移动时,我试图不断地阅读坐标。
-
什么在移动指针?苹果铅笔?
-
外部指点设备(鼠标/触控板)。我会将其添加到帖子中以澄清。
-
本教程没有向您展示您正在尝试做什么吗?