gpt4 book ai didi

SwiftUI DragGesture 仅在一个方向

转载 作者:行者123 更新时间:2023-12-04 05:04:42 41 4
gpt4 key购买 nike

我希望 SwiftUI DragGesture 仅在手势处于特定方向(水平/垂直)时启动。是否可以?

最佳答案

是的,它是通过将手势平移的两个组件(水平或垂直)之一应用于 View 偏移。

这是作为 ViewModifier 实现的这种行为.

struct DraggableModifier : ViewModifier {

enum Direction {
case vertical
case horizontal
}

let direction: Direction

@State private var draggedOffset: CGSize = .zero

func body(content: Content) -> some View {
content
.offset(
CGSize(width: direction == .vertical ? 0 : draggedOffset.width,
height: direction == .horizontal ? 0 : draggedOffset.height)
)
.gesture(
DragGesture()
.onChanged { value in
self.draggedOffset = value.translation
}
.onEnded { value in
self.draggedOffset = .zero
}
)
}

}

演示:

struct ContentView: View {

var body: some View {
VStack {
Spacer(minLength: 100)
HStack {
Rectangle()
.foregroundColor(.green)
.frame(width: 100, height: 100)
.modifier(DraggableModifier(direction: .vertical))
Text("Vertical")
}
Spacer(minLength: 100)
Rectangle()
.foregroundColor(.red)
.frame(width: 100, height: 100)
.modifier(DraggableModifier(direction: .horizontal))
Text(verbatim: "Horizontal")
Spacer(minLength: 100)
}
}
}


结果 :

enter image description here

关于SwiftUI DragGesture 仅在一个方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58237325/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com