简体   繁体   English

ios - 如何在 UICollectionView 中加载更多对象

[英]ios - How to load more object in UICollectionView

I have a collection view and data to load.我有一个集合视图和数据要加载。 My goal is when the collection view loaded it's load only first 5 items.我的目标是当集合视图加载时它只加载前 5 个项目。 And when I scroll to bottom of collection view it's load more 5 items and again until load all the data.当我滚动到集合视图的底部时,它会加载更多 5 个项目,然后再次加载,直到加载所有数据。

// The data to load (It already have 20 item loaded from server)
static var productInfo: [ProductInfo] = []

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MainProductCell.reuseIdentifier, for: indexPath) as? MainProductCell else {
        fatalError("Expected `\(MainProductCell.self)` type for reuseIdentifier \(MainProductCell.reuseIdentifier). Check the configuration in Main.storyboard.")
    }
        // Set data for collection cell
        cell.modelId = String(ProductCollectionViewController.productInfo[indexPath.row].productId)
        cell.modelName = String(ProductCollectionViewController.productInfo[indexPath.row].name)
        cell.modelPrice = String(ProductCollectionViewController.productInfo[indexPath.row].price)
        cell.modelImage = ProductCollectionViewController.productInfo[indexPath.row].image
        cell.objectImageView.downloadedFrom(link: ProductCollectionViewController.productInfo[indexPath.row].image, contentMode: UIViewContentMode.scaleAspectFit)
        cell.modelLink = String(ProductCollectionViewController.productInfo[indexPath.row].remoteStorage)
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    let lastItem = ProductCollectionViewController.productInfo.count - 1
    if indexPath.row == lastItem {
        loadMore()
    }
}

func loadMore() {
    print("load more...")
    //How to handle load more here?
}

How to handle the loadMore() function?如何处理 loadMore() 函数? Thank you.谢谢。

Till that it's going well plus直到一切顺利

  if indexPath.row == lastItem && !loading {
    loading = true
    loadMore()
}

Using itemAtIndexIndexPath to determine the last cell is not the best way, you should check when the scrollView is going to scroll to bottom.使用 itemAtIndexIndexPath 来确定最后一个单元格不是最好的方法,您应该检查 scrollView 何时滚动到底部。

var isScrolledToBottomWithBuffer: Bool {
    let buffer = tableView.bounds.height - tableView.contentInset.top - tableView.contentInset.bottom
    let maxVisibleY = tableView.contentOffset.y + self.tableView.bounds.size.height
    let actualMaxY = tableView.contentSize.height + tableView.contentInset.bottom
    return maxVisibleY + buffer >= actualMaxY
}

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if( scrollView.contentSize.height == 0 ) {
        return;
    }
    if isScrolledToBottomWithBuffer {
        self.loadMore()
    }
}

Improving upon @duytph answer改进@duytph 答案

    var isAllowedToFetchNewDataFromBottom = false

...

        var products: [Products] = []

            ...

            collectionView.delegate = self

            ...

            extension AuthorProductsListViewController: UICollectionViewDelegate {

                func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
                    if scrollView.contentSize.height == 0 {
                        return
                    }
                    if isScrolledToBottomWithBuffer, isAllowedToFetchNewDataFromBottom {
                        fetchNewData() {
                            self.isAllowedToFetchNewDataFromBottom = false
                        }
                    }
                }

                func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
                    lastItemCount = pendingProducts.count

                    if indexPath.row == lastItemCount - 1 {
                        isAllowedToFetchNewDataFromBottom = true
                    }
                }

                var isScrolledToBottomWithBuffer: Bool {
                    let buffer = collectionView.bounds.height - collectionView.contentInset.top - collectionView.contentInset.bottom
                    let maxVisibleY = collectionView.contentOffset.y + self.collectionView.bounds.size.height
                    let actualMaxY = collectionView.contentSize.height + collectionView.contentInset.bottom
                    return maxVisibleY + buffer >= actualMaxY
                }

            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在UICollectionView中添加加载更多单元格? - How to add Load more cell in UICollectionView? UICollectionView加载更多数据 - UICollectionView load more data 如何在iOS的同一UICollectionView中加载图像和视频 - How to load images and videos in same UICollectionView in iOS 如何在UICollectionView中加载更多数据而不重新加载所有数据 - How to load more data in UICollectionView without reloading all data UICollectionView:如何使用dequeueReusableCellWithReuseIdentifier加载比屏幕大小更多的单元格? - UICollectionView: how to load more cells than the screen size using dequeueReusableCellWithReuseIdentifier? iOS:将新数据加载到UICollectionView - ios: load new data into UICollectionView UICollectionView在顶部加载项 - 加载更多选项 - UICollectionView load items on top - load more option UIColreshView底部的UIRefreshControl(加载更多数据) - UIRefreshControl at Bottom of UICollectionView (load more data) iOS-如何将更多的数据库记录加载到UIWebView? - IOS - How to load more DB records to UIWebView? 如何使用 swift 在 UICollectionView 中添加“拉动刷新”/“加载更多”? (垂直和水平) - How to add 'Pull to refresh'/ 'Load more' in UICollectionView using swift? (for both vertical and horizontal)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM