Правильный способ обновления данных об обновлениях View DataSource для нескольких вызовов Swift 5IOS

Программируем под IOS
Ответить
Anonymous
 Правильный способ обновления данных об обновлениях View DataSource для нескольких вызовов Swift 5

Сообщение Anonymous »

У меня есть представление о сборе, и я загружаю 20 ячеек в каждом вызове ( извлекая ) из Firebase в нем. Таким образом, у меня есть два раздела, в которых первый раздел - это номер счета моего исходного массива, а второй раздел просто показывает ячейку загрузки, когда Bool Значение получает больше true.
Это код представления коллекции:

Это код представления коллекции:

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

extension ProductViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return self.objectArray.count
} else if section == 1 {
return fetchingMore ? 1 : 0
}
return 0
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
cellHeights[indexPath] = cell.frame.size.height
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
var minimumLineSpacingForSectionAt: CGFloat
if section == 0 {
minimumLineSpacingForSectionAt = -50
} else {
minimumLineSpacingForSectionAt = 0
}
return minimumLineSpacingForSectionAt
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 0 {
return CGSize(width: productCollectionView.bounds.width, height: CommonService.heightForRowAtIndexPathForiPhones(cellType: .itemCell))
} else {
return CGSize(width: productCollectionView.bounds.width, height: 70)
}
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemAlbumCollectionViewCell", for: indexPath) as! ItemAlbumCollectionViewCell
cell.setUpCell(product: objectArray[indexPath.row]!)
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LoadingCollectionViewCell", for: indexPath) as! LoadingCollectionViewCell
cell.activityIndicator.startAnimating()
return cell
}
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let productCategoryViewController = Storyboards.ProductCategoryVC.controller as! ProductCategoryViewController
productCategoryViewController.products = objectArray[indexPath.row]!
pushViewController(T: productCategoryViewController)
}

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

switch kind {
case UICollectionView.elementKindSectionHeader:
guard let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "StreachyCollectionHeaderReusableView", for: indexPath) as? StreachyCollectionHeaderReusableView else { fatalError("Invalid view type") }
return headerView
default:
assert(false, "Invalid element type")
}
}
}
< /code>
и эта функция, которая требуется для получения данных: < /p>
func pagination(forDivisionCollection: String) {
fetchProduct(forDivisionCollection: forDivisionCollection, completion: { newData in
self.productCollectionView.reloadSections(IndexSet(integer: 1))
self.objectArray.append(contentsOf: newData)
self.endReached = newData.count == 0
self.fetchingMore = false

UIView.performWithoutAnimation {
self.productCollectionView.reloadData()
}
})
}
и он работает отлично. Нажатия в этом разделе Функция Func Pagination (FordivisionCollection: String) будет вызвана с помощью параметра, и она будет отфильтровать источник данных с помощью этого параметра и заполнить источник данных в соответствии с опцией Top Menu, как это:

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

func pagination(isForNewDivision: Bool, forDivisionCollection: String) {
self.fetchingMore = true
if isForNewDivision == true {
self.objectArray.removeAll()
}
fetchProduct(forDivisionCollection: forDivisionCollection, completion: { newData in
self.productCollectionView.reloadSections(IndexSet(integer: 1))
self.objectArray.append(contentsOf: newData)
self.endReached = newData.count == 0
self.fetchingMore = false

UIView.performWithoutAnimation {
self.productCollectionView.reloadData()
}
})
}
Но я получаю неверное обновление: неверное количество элементов в разделе 0. Предупреждение на Xcode при запуске его в симуляторе, и оно разбивается на физическом устройстве. Я немного исследовал и придумал решение использования recormbatchupdates , но ни один из них не работает. Итак, мой вопрос в такой ситуации, что было бы идеальным способом извлечения данных и загрузки в представлении сбора?

Подробнее здесь: https://stackoverflow.com/questions/592 ... ll-swift-5
Ответить

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

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

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

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

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