Post

Replies

Boosts

Views

Activity

UIKit in SwiftUI memory leak while displaying images
I'm using UIKit to display a long list of large images inside a SwiftUI ScrollView and LazyHStack using UIViewControllerRepresentable. When an image is loaded, I'm using SDWebImage to load the image from the disk. As the user navigates through the list and continues to load more images, more memory is used and is never cleared, even as the images are unloaded by the LazyHStack. Eventually, the app reaches the memory limit and crashes. This issue persists if I load the image with UIImage(contentsOfFile: ...) instead of SDWebImage. How can I free the memory used by UIImage when the view is removed? ScrollView(.horizontal, showsIndicators: false) { LazyHStack(spacing: 16) { ForEach(allItems) { item in TestImageDisplayRepresentable(item: item) .frame(width: geometry.size.width, height: geometry.size.height) .id(item.id) } } .scrollTargetLayout() } import UIKit import SwiftUI import SDWebImage class TestImageDisplay: UIViewController { var item: TestItem init(item: TestItem) { self.item = item super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) imageView.center = view.center view.addSubview(imageView) imageView.sd_setImage(with: item.imageURL, placeholder: nil) } } struct TestImageDisplayRepresentable: UIViewControllerRepresentable { var item: TestItem func makeUIViewController(context: Context) -> TestImageDisplay { return TestImageDisplay(item: item) } func updateUIViewController(_ uiViewController: TestImageDisplay, context: Context) { uiViewController.item = item } }
0
0
297
Sep ’24