I have a parent view that conditionally displays a subview:
struct HomeView: View {
@State var selectedView = true
var body: some View {
VStack {
Picker("Selected", selection: $selectedView) {
Text("A").tag(true)
Text("B").tag(false)
}.pickerStyle(SegmentedPickerStyle())
if selectedView {
SubView()
} else {
Text("Other")
}
}
}
}
My subview contains an AsyncImage
that loads from a URL:
struct SubView: View {
private let url = URL(string: "some url here")
var body: some View {
AsyncImage(url: url)
}
}
My issue is that SubView
is recreated every time I switch the picker to B and then back to A. This recreates the AsyncImage
and causes a reload from the URL, which is not necessary.
Is there a way to prevent SubView
from being recreated here? I notice that TabView
does not seem to recreate its containing views when switching between them. Is it possible to get this functionality using the structure I have?
I have tried making SubView
equatable and using the .equatable()
modifier on its instance as such:
if selectedView {
SubView().equatable()
} else {
Text("Other")
}
However, the image is still reloaded.