问题描述
我正在尝试找出一种解决方案,为 x 轴和 y 轴(想想计算机触控板)创建一个 2D 滑块,以便我可以根据用户是水平拖动还是垂直拖动来更改不同的值。
感谢我能得到的任何帮助/想法。
提前致谢。
解决方法
您可以为此使用 .gesture(DragGesture().onChanged())
struct ContentView: View {
var body: some View {
ZStack {
Text("Test")
}
.gesture(DragGesture()
.onChanged({ value in
print("x: \(value.location.x)")
print("y: \(value.location.y)")
})
)
}
}
更新: 在评论中提问:“我希望它们在 0.01 到 1.0 的范围内,你有没有机会知道如何解决这个问题?”
解决方案: 例如(value.location.x / UIScreen.main.bounds.width)
struct ContentView: View {
var body: some View {
ZStack {
Color.blue
.edgesIgnoringSafeArea(.all)
Text("Test")
}
.frame(width: UIScreen.main.bounds.width,height: UIScreen.main.bounds.height)
.gesture(DragGesture()
.onChanged({ value in
print("x: \(value.location.x / UIScreen.main.bounds.width)")
print("y: \(value.location.y / UIScreen.main.bounds.height)")
})
)
}
}
十进制限量版
struct ContentView: View {
var body: some View {
ZStack {
Color.blue
.edgesIgnoringSafeArea(.all)
Text("Test")
}
.frame(width: UIScreen.main.bounds.width,height: UIScreen.main.bounds.height)
.gesture(DragGesture()
.onChanged({ value in
let valueX = String(format: "%.2f",value.location.x / UIScreen.main.bounds.width)
let valueY = String(format: "%.2f",value.location.y / UIScreen.main.bounds.height)
print("x: \(valueX)")
print("y: \(valueY)")
})
)
}
}