3

I have a very simple app: 4,000 images(400x400 in .jpg) that need to display 3 in a row. All images a stored in file storage and are equal 1/3 of device width so I don't need to resize/rescale it but display as is.

Here is a body code:

var body: some View {
    ScrollView {
        LazyVGrid(columns: Array(repeating: GridItem(.fixed(size), spacing: 1), count: 3),
                  alignment: .center,
                  spacing: 0) {
            ForEach(controller.newAlbums, id: \.self) { album in
                PhotoThumbnailView(filePath: album)
            }
        }
    }
    .task {
        controller.loadUserAlbums()
    }
}

let size = UIScreen.main.bounds.width/3

struct PhotoThumbnailView: View {
    @State private var image: Image?
    @State private var imageFileURL: String
    
    init(filePath: String) {
        self.imageFileURL = filePath
    }
    
    func readFromFile(){
        if let uiImage = UIImage(contentsOfFile: imageFileURL) {
            self.image = Image(uiImage: uiImage)
        }
    }
    
    var body: some View {
        ZStack {
            if let img = image {
                img
            } else {
                Rectangle()
                    .foregroundColor(.clear)
                    .frame(width: size, height: size)
                ProgressView()
            }
        }
        .task({
            readFromFile()
        })
        .onDisappear {
            image = nil
        }
    }
}

The problem is that when I scroll down (even vary slowly) it lagging and the scrolling animation is not smooth. How to resolve the issue above?

Serge
  • 2,031
  • 3
  • 33
  • 56
  • `UIImage(contentsOfFile:` on the main thread like this is likely to slow things down. You'd probably want to pre-load/cache the images. – jnpdx Oct 27 '22 at 22:40
  • [side issue: how can the images all be 1/3 of the width of the device when there are multiples widths of device?] – flanker Oct 27 '22 at 23:46
  • this code should work only on one type of device iphone 13 pro. No other device will be used. That's why. – Serge Oct 28 '22 at 15:24
  • 2
    Caching helps, but LazyVGrid performance is terrible. Not sure how apple expects real apps to use it. ‍♂️ – zumzum Nov 03 '22 at 00:47

0 Answers0