'How to implement edge drag forward/backward navigation in SwiftUI?
I'm trying to implement gesture-based navigation to show/hide detail views similar to how iOS Safari has screen edge gestures for forward/back. Here is a video for clarification of what I mean.
In essence, when new views are added to the stack, they enter from the right covering the original view. Once business with the new view is concluded, it may be dismissed by swiping from the left edge. A recently dismissed view may be brought back by swiping from the right edge.
I currently have implemented a solution for two views to mimic the feel of the navigation, however I wish to extend what I have to an arbitrary number of views - including views which may be dynamically added later.
var body: some View {
ZStack {
SomeView()
.gesture(DragGesture().onChanged({ gesture in
if gesture.startLocation.x > UIScreen.main.bounds.width - 10.0 {
layer2offset = gesture.location.x
}
}).onEnded({ gesture in
if layer2offset <= UIScreen.main.bounds.width/2 {
layer2offset = 0
layer2Showing = true
} else {
layer2offset = UIScreen.main.bounds.width
layer2Showing = false
}
}))
SomeView()
.offset(x: layer2offset, y: 0)
.animation(.easeInOut(duration: 0.2), value: layer2offset)
.gesture(DragGesture().onChanged({ gesture in
if gesture.startLocation.x < 10.0 {
layer2offset = gesture.location.x
}
}).onEnded({ gesture in
if layer2offset >= UIScreen.main.bounds.width/2 {
layer2offset = UIScreen.main.bounds.width
layer2Showing = false
} else {
layer2offset = 0
layer2Showing = true
}
}))
}
}
I've tried expanding this by breaking out the gesture logic into SomeView so that each view handles its own positioning and logic. However, breaking out the logic caused dismissed views to be unable to come back (I think this has something to do with how .gesture works). I'm assuming that I need to have some root view handle all the positioning and gesture recognition. However, I'm unsure of how to have the root view control all of the sub views. I'm new to Swift and SwiftUI and I feel there's some feature in Swift or SwiftUI that I don't know about that would help in this case. Any pointers are appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
