In my game NBackGame, I implemented ScrollView and ScrollViewReader to scroll up every time users taps the button.
However, I noticed that sometime after closing the window with those Scroll views there is a random crash, like that on the screen, it’s Thread 1: EXC_BAD_ACCESS using ScrollViewReader.
I didn’t find what’s exactly wrong with this view but I found that the problem is with scrolling.
I had an array of views and always one from these views was displayed and ScrollViewReader was scrolled to the top of that view after button tap.
The exact code you can find here is because it comes from my open source project. Here, I share only the most important part of that code.
Previously I had:
ScrollView(showsIndicators: false) {
ScrollViewReader { viewReader in
ZStack {
Color.black.ignoresSafeArea()
VStack {
steps[viewModel.currentStep]
.id(tutorialContentId)
}
}
.onChange(of: scrollToIndex) { _ in
withAnimation {
viewReader.scrollTo(tutorialContentId, anchor: .top)
}
}
//.. the rest of code
The most important parts of that code are underlined with red color, there is the id for an array of view and scrollTo with an anchor.
The solution or the hack is to create an empty view, I used Text without any text because EmptyView doesn’t work well and remove anchor from scrollTo.
New code:
ScrollViewReader { viewReader in
ScrollView(showsIndicators: false) {
VStack {
Text(“”)
.id(tutorialContentId)
steps[viewModel.currentStep]
}
.onChange(of: viewModel.currentStep) { _ in
withAnimation {
viewReader.scrollTo(tutorialContentId)
}
}
}
//.. the rest of code
Now that random crash doesn’t appear anymore. If you want to see all changes with real code here is commit with that change.