SwiftUI 中的二维 Slider/Trackpad

2D Slider/Trackpad in SwiftUI

我正在尝试找出一种解决方案来为 x 轴和 y 轴(想想计算机触控板)创建一个 2D 滑块,这样我就可以根据用户是水平拖动还是垂直拖动来更改不同的值。

我很感激任何我能得到的help/ideas。

提前致谢。

你可以使用 .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)")
                        
                    })
        )
    }
}