【发布时间】:2021-06-01 16:44:57
【问题描述】:
【问题讨论】:
-
到目前为止你尝试了什么?
-
我使用了 DragGesture,但它不能完全水平移动矩形
【问题讨论】:
您可以像这样滑动到操作按钮。您可以根据需要自定义和优化代码。
在 XCode 12.3 和 iOS 14.3 中测试
typealias FrontView<V> = Group<V> where V:View
typealias BackView<V> = Group<V> where V:View
struct SwipeButton<Content: View, BackContent: View>: View {
private var content: () -> TupleView<(FrontView<Content>, BackView<BackContent>)>
@State private var offset = CGSize.zero
private let onAction: () -> ()
init(@ViewBuilder content: @escaping () -> TupleView<(FrontView<Content>, BackView<BackContent>)>, onAction: @escaping () -> Void) {
self.content = content
self.onAction = onAction
self.content = content
}
var body: some View {
let (frontView, backView) = self.content().value
return GeometryReader { (geometry) in
ZStack {
backView
frontView
.offset(self.offset)
.gesture(DragGesture(minimumDistance: 30, coordinateSpace: .local)
.onChanged { gestrue in
if gestrue.translation.width < 0 {
self.offset.width = gestrue.translation.width
}
print(offset)
}
.onEnded { value in
if value.translation.width < 0 {
self.offset.width -= geometry.size.width
onAction()
}
}
)
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.animation(.spring())
}
}
用法
struct SwipeDemoView: View {
var body: some View {
SwipeButton {
// Add your fron view
FrontView {
Text("Swipe").frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.black).foregroundColor(Color.white)
}
// Add your back view
BackView {
Text("Accepted")
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.green)
}
} onAction: {
print("Swiped...")
}
.frame(width: 200, height: 50)
.cornerRadius(15)
}
}
【讨论】: