I'm attempting to implement a swipe functionality left/right where I want the user to swipe left/right between views (in this example the circle and rectangle). While I have the left/right detecting and switching between views working I am not sure how to implement it so that as a user drags for example left, the user slowly sees the next view until it snaps into place.
Here's what it currently looks like and the code.
struct Swipe: View {
@State private var xOffset: CGFloat = 0.0
@State private var showCircle: Bool = false
@State private var showRectangle: Bool = true
var body: some View {
VStack {
Text("Current xOffset: \(xOffset)")
ZStack {
if showCircle {
Circle()
.frame(width: 250, height: 250)
}
if showRectangle {
Rectangle()
.foregroundColor(Color.red)
.frame(width: 100, height: 100)
.offset(x: xOffset)
}
}
.gesture(
DragGesture()
.onChanged {
value in
withAnimation(Animation.spring()) {
xOffset = value.translation.width
}
}
.onEnded { value in
if value.predictedEndLocation.x < -100 || value.predictedEndLocation.x > 100 {
showCircle.toggle()
showRectangle.toggle()
}
xOffset = 0.0
}
)
}
}
}
But what I want is the transition during the DragGesture
. I've tried to draw it as best as I can where that black color is the background while it's transitioning to the next view.
Any help is appreciated, thank you.
CodePudding user response:
If you want your animation like paging, use TabView:
TabView(selection: $selectedPage) {
ForEach(pageList, id: \.self) { page in
if page == .circle {
CircleView()
} else {
RectangleView()
}
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
Remember if pageList's type is Array<T>
then selectedPage's type must be T