Hi everyone I'm working on a horizontal scrolling with views placed inside a ZStack
The positions of the overlapping views are handled by an offset
like this
Test1(currentIndex: $currentIndex, size: size)
.offset(x: -size.width * CGFloat((currentIndex - view)))
In overlay above the ZStack
I added a "Next" button which assigns a value of +1 to the variable currentIndex
in order to manage the view display
Everything seems to work fine but I have a problem that I would like to be able to solve.
Each view that is presented has a scrollview
which manages the content of the view .
I'll give you an example for convenience in this example I will call the views by assigning the currentIndex
value for you to understand better:
The first view is presented when currentIndex == 0
. The user scrolls the contents of View0 and pushes the next button to show the view with currentIndex == 1
(View1).
If the user returns to currentIndex == 0
by pushing the back button, the contents of View0 remain in the position where the user left it ...
At this point I would like that when the user navigates between the views and goes back to the previous view (for a modification of the data that he has entered) the contents of the scrollview return to the initial position and not as he left it before pushing the next button
I hope I was able to explain myself well if you need information because I wasn't clear enough, just ask
This is my code
struct Test1: View {
@Binding var currentIndex: Int
var size: CGSize
var body: some View {
ScrollView {
VStack(spacing: 40) {
VStack(alignment: .leading, spacing: 16) {
Text("Title ")
.font(.comfortaa(.bold, size: .title))
Text("Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo")
.font(.comfortaa(.regular, size: .body))
}
.lineSpacing(5)
ForEach(0..<10, id:\.self) { _ in
Rectangle()
.stroke()
.frame(height: 100)
}
}
}
}
}
struct ExamInsertionView: View {
@State private var currentIndex: Int = 0
var body: some View {
GeometryReader {
let size = $0.size
ZStack {
ForEach(0..<3, id:\.self) { view in
Test1(currentIndex: $currentIndex, size: size)
.offset(x: -size.width * CGFloat((currentIndex - view)))
.animation(.interactiveSpring, value: currentIndex)
}
}
.overlay(alignment: .bottom) {
HStack {
Button("Back") {
if currentIndex > 0 {
currentIndex -= 1
}
}
Spacer()
Button("Avanti") {
if currentIndex < 2 {
currentIndex += 1
} else { currentIndex = 0 }
}
}
.bold()
.foregroundColor(.white)
.padding(24)
.background(.blue)
.padding(.bottom, 40)
}
}
}
}