Проблема с распределением памяти с помощью LazyVGrid SwiftUI при отображении медиафайловIOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Проблема с распределением памяти с помощью LazyVGrid SwiftUI при отображении медиафайлов

Сообщение Anonymous »


Сейчас я работаю над приложением SwiftUI, которое отображает медиафайлы в сетке с включенным LazyVGrid.

Код: Выделить всё

GalleryView
where there will be 3 media files per row. The media files are loaded from the app's cache and not from the user's app. When user scrolls down to see more media data, media files are lazily loaded into memory and the ones hidden from view are not deallocated from memory because LazyVGrid does not have a built-in memory deallocation mechanism. Проблемы с памятью становятся более очевидными ( where is the number of media files) when there exists a large number of images or videos to show on appear of

Код: Выделить всё

GalleryView
:

Код: Выделить всё

struct GalleryView: View {
@Binding var mediaFiles: [Media]
var body: some View {
GeometryReader { geometry in
ScrollView {
let width = geometry.size.width / 3 - 10
let gridItemLayout = [GridItem(.fixed(width)), GridItem(.fixed(width)), GridItem(.fixed(width))]
LazyVGrid(columns: gridItemLayout, spacing: 10) {
ForEach(mediaFiles, id: \.id) { media in
if let image = media.image {
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(width: width)
} else if let videoURL = media.videoURL {
// Display video thumbnail here
}
}
}
}
}
}
}

struct Media: Identifiable {
let id = UUID()
let creationTime: Date
var image: UIImage?
var videoURL: URL?
}
I have tried a custom UIKit approach to handle the memory deallocation issue:

Код: Выделить всё

struct CollectionView: UIViewControllerRepresentable {
typealias UIViewControllerType = UICollectionViewController

@Binding var mediaFiles: [Media]
var width: CGFloat

func makeUIViewController(context: Context) -> UICollectionViewController {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: width / 3, height: width / 3)
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10
let collectionViewController = UICollectionViewController(collectionViewLayout: layout)
collectionViewController.collectionView?.register(MediaCell.self, forCellWithReuseIdentifier: "cell")
collectionViewController.collectionView?.backgroundColor = .white
return collectionViewController
}

func updateUIViewController(_ uiViewController: UICollectionViewController, context: Context) {
uiViewController.collectionView?.dataSource = context.coordinator
uiViewController.collectionView?.delegate = context.coordinator
uiViewController.collectionView?.reloadData()
}

func makeCoordinator() -> Coordinator {
Coordinator(self)
}

class Coordinator: NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
var parent: CollectionView

init(_ parent: CollectionView) {
self.parent = parent
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return parent.mediaFiles.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MediaCell
let media = parent.mediaFiles[indexPath.row]
if let image = media.image {
cell.imageView.image = image
}
return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Handle selection here
}
}
}
so that I can use

Код: Выделить всё

CollectionView
in place of LazyVGrid in

Код: Выделить всё

GalleryView
like this:

Код: Выделить всё

CollectionView(mediaFiles: $mediaFiles, width: width)
.frame(width: geometry.size.width, height: geometry.size.height)
.onAppear {
model.loadMediaFiles()
if let lastMediaIndex = mediaFiles.indices.last {
scrollView.scrollTo(lastMediaIndex, anchor: .bottom)
}
}
But the custom UIKit code didn't work as expected because

Код: Выделить всё

GalleryView
now shows a blank white screen (on either light/dark mode) instead of showing 3 media items per row. I have also tried using List in place of LazyVGrid, or trying Chris C's code to try optimizing the memory complexity of the problem to but neither approach worked. Я также попытался разбить данные на части и создать строки с более чем одним изображением, как было предложено @baronfac в другой теме. Однако предложение @baronfac оптимизирует проблему с памятью только за счет to , which this linear reduction doesn't really change the memory complexity of the problem since it's still .
Is there a simple and intuitive way to deal with this absence of memory deallocation issue with LazyVGrid? If a UIKit implementation is the best approach, could someone help identify what’s wrong with my current UIKit code that’s causing the GalleryView to display a blank screen?


Источник: https://stackoverflow.com/questions/781 ... edia-files
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Проблема с распределением памяти с помощью LazyVGrid SwiftUI при отображении медиафайлов
    Гость » » в форуме IOS
    0 Ответы
    53 Просмотры
    Последнее сообщение Гость
  • Как я могу использовать LazyVGrid SwiftUI для создания карточек гибкой ширины в разных строках?
    Anonymous » » в форуме IOS
    0 Ответы
    36 Просмотры
    Последнее сообщение Anonymous
  • Проблема LazyVGrid и ScrollTo в SwiftUI
    Anonymous » » в форуме IOS
    0 Ответы
    34 Просмотры
    Последнее сообщение Anonymous
  • Swiftui LazyVgrid против пользовательского просмотра для выбираемых тегов (ошибка эффекта глюка)
    Anonymous » » в форуме IOS
    0 Ответы
    18 Просмотры
    Последнее сообщение Anonymous
  • Swiftui LazyVgrid против пользовательского просмотра для выбираемых тегов (ошибка эффекта глюка)
    Anonymous » » в форуме IOS
    0 Ответы
    16 Просмотры
    Последнее сообщение Anonymous

Вернуться в «IOS»