CodexBloom - Programming Q&A Platform

Unexpected UI Lag When Using UICollectionView with Async Image Loading in SwiftUI

πŸ‘€ Views: 79 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
swiftui kingfisher uicollectionview performance swift

I'm integrating two systems and I'm having trouble with Quick question that's been bugging me - I'm experiencing significant UI lag when I load images asynchronously in a `UICollectionView` that uses SwiftUI..... I'm using `Kingfisher` for image loading, and though it works, the UI becomes unresponsive during image fetching, especially when scrolling through many items quickly. Here's a simplified version of my setup: ```swift import SwiftUI import Kingfisher struct ImageCell: View { var imageURL: URL var body: some View { KFImage(imageURL) .placeholder { ProgressView() } .resizable() .aspectRatio(contentMode: .fill) .frame(width: 100, height: 100) .clipped() } } struct ImageGridView: View { let urls: [URL] var body: some View { GridView(data: urls) { url in ImageCell(imageURL: url) } } } struct ContentView: View { let imageUrls: [URL] = [...] var body: some View { ImageGridView(urls: imageUrls) } } ``` I've ensured that my image fetching is happening on a background thread, and I've set up caching properly with `Kingfisher`, but the scroll performance is still choppy. I've tried profiling my app with Instruments, and I can see spikes in CPU usage when images are loaded. Here’s the profiling result where it shows a high CPU usage during scrolling: - **Main Thread Usage:** Spikes to 90% during image loading. - **Rendering Time:** Average of 15ms per frame when loading new images. I also attempted to wrap the `KFImage` in a `LazyVGrid` instead of a standard `UICollectionView`, but the issue persists. Any suggestions on best practices to optimize performance for this scenario? Are there any specific configurations or techniques I might have overlooked? I'm working on a web app that needs to handle this. Has anyone else encountered this? Any ideas what could be causing this? I've been using Swift for about a year now. Any ideas how to fix this? Is there a simpler solution I'm overlooking?