I have a ScrollView
containing a ForEach
iterating through an array of elements of type Verse
. Each view within the ForEach
is a VStack
with some Arabic text and some English text.
The English text is only visible when readingMode
is false
. The Arabic text becoms aligned to the centre when readingMode
is false
There are 3 parts to the problem:
- When the device is rotated, the view does not maintain the scroll position
- When the view appears, there may be an initial scroll position (a verse which the view should start at)
- I want to be able to update the scroll position based on a selected verse within a wheel picker
Here is a simplified example of the code I have that contains only the essential parts of the view. Please let me know if you need any more information.
ScrollView {
ForEach(verses) { verse in
VStack {
HStack {
if !readingMode {
Spacer()
}
Text("Some Arabic Text")
}
if !readingMode {
Text("Some English Text")
}
}.id(verse.id)
}
}
I have tried using modifiers such as .onChange
in combination with UIDevice.current.orientation
and the .scrollPosition
modifer to get the scroll position before rotation and set that as the scroll position after rotation but this is very buggy and often doesn't work
I have managed to achieve part 2 and 3 of the problem using a ScrollViewReader
and the scrollTo
function but the ScrollView
can, as a result, randomly jump to a different part of the view for seemingly no reason.
From what I have found online through many hours of research, SwiftUI should automatically maintain the scroll position when the device is rotated so I might be doing something completely wrong that is causing all my problems.
Thanks in advance for your help!
EDIT: MORE SPECIFIC CODE
The following code more accurately represents my specific context which could have an affect on possible solutions
ScrollView {
Text("Some Header")
LazyVStack {
ForEach(verses) { verse in
VStack {
HStack {
if !readingMode {
Spacer()
}
Text(verse.arabic)
.multilineTextAlignment(readingMode ? .center : .trailing)
}
if !readingMode {
HStack {
Text(verse.english)
.multilineTextAlignment(.leading)
Spacer()
}
}
Divider()
}
.id(verse.id)
}
}
}