I need to create a screen that displays an Array of sentences in a List.
The Array can be very long and the user cannot read it all at once.
Therefore, the following features are needed:
- save the index of the currently displayed cell each time the user scrolls
- scroll to the cell with the saved index when the user opens the screen again
I have seen that the functionality of 2. can be easily implemented using .scrollTo
in ScrollViewProxy
(ScrollViewReader
).
I am not sure how to implement the function of 1.
It is possible for users to bookmark cells by tapping on them themselves, but the user experience is compromised.
It should be saved automatically.
For example, in the scrolling state of the image below, I would like to get the index of 435, which is the last cell fully displayed.
import SwiftUI
private let lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
struct ContentView: View {
@State private var largeTextArray: [String] = (0..<500).map { _ in
String(repeating: lorem, count: Int.random(in: 3..<10))
}
var body: some View {
List {
ForEach(largeTextArray.indices, id: \.self) { index in
Text("\(index): ")
.font(.title)
.fontWeight(.heavy)
+ Text(largeTextArray[index])
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Any ideas are welcome.
Must support iOS 16 or later.