[英]How to prevent recreating a conditional view in SwiftUI?
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:我的子视图包含一个从
AsyncImage
加载的 AsyncImage:
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.我的问题是每次将选择器切换到 B 然后再切换回 A 时都会重新创建
SubView
。这会重新创建AsyncImage
并导致从 URL 重新加载,这不是必需的。
Is there a way to prevent SubView
from being recreated here?有没有办法防止在这里重新创建
SubView
? I notice that TabView
does not seem to recreate its containing views when switching between them.我注意到
TabView
在它们之间切换时似乎没有重新创建其包含的视图。 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:我尝试使
SubView
可等价并在其实例上使用.equatable()
修饰符,如下所示:
if selectedView {
SubView().equatable()
} else {
Text("Other")
}
However, the image is still reloaded.但是,图像仍会重新加载。
Either get rid of the if
that creates a _ConditionView
and use a modifier instead, or enable the URLSession
's URLCache
so the image is cached in memory on or disk and isn't actually downloaded again.要么摆脱创建
_ConditionView
的if
并改用修饰符,要么启用URLSession
的URLCache
以便图像缓存在 memory 或磁盘上,并且实际上不会再次下载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.