I make a simple app for displaying image list. I use a LazyVStack inside ScrollView as container, ForEach to load every image Images are loading from network, I have tried AsyncImage, but AsyncImage always loads image from network and no cache. I have tried using SDWebImageSwiftUI and CachedAsyncImageView, both of them can get image from network with cache, and using lots of memory while scroll image. here is the code
import CachedAsyncImage
import SDWebImageSwiftUI
struct ContentView: View {
@State private var imageURLList: [String] = []
var body: some View {
GeometryReader { geometryProxy in
VStack {
HStack{
Button("test load") {
// parse the image list
Task{
do{
self.imageURLList = try await ImageListLoader.parseImageUrlList()
} catch {
print("error:\(error)")
}
}
}
Spacer()
Button("clear") {
self.imageURLList.removeAll()
}
}
ScrollView {
LazyVStack(spacing: 0) {
ForEach(self.imageURLList, id: \.self) { url in
WebImage(url: URL(string: url))
.resizable()
.scaledToFit()
.frame(width: geometryProxy.size.width)
}
}
}
}
}
.padding()
}
}
I have tried to same url in forEach, and no memery issue
ScrollView {
LazyVStack(spacing: 0) {
ForEach(self.imageURLList, id: \.self) { url in
WebImage(url: URL(string: url))
.resizable()
.scaledToFit()
.frame(width: geometryProxy.size.width)
}
}
}
Use
List
instead of LazyVStack this will manage the memory automatically as it works likeUITableView
in the UIKit. In LazyVStack it will load the images at the same time as you scroll down & keep it in the memory for the duration.