微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SwiftUI 中的 2D 滑块/触控板

如何解决SwiftUI 中的 2D 滑块/触控板

我正在尝试找出一种解决方案,为 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)")
                    })
        )
    }
}

enter image description here


更新: 在评论中提问:“我希望它们在 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)")
                    })
        )
    }
}

enter image description here


十进制限量版

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

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。