如何加载更多的collectionview?

问题描述:

我有一个支持分页的api。如何加载更多的collectionview?

"pagination":{ 
    "total":355, 
    "totalPages":10, 
    "page":1, 
    "nextPage":2, 
    "nextPageUrl":"http://api..................?page=2" } 

我的目标是将nextPageUrl的图像添加到我的collectionview。 那么我该如何做到这一点?

任何建议或代码示例?我是swift新手。非常感谢:)

您需要在集合视图的末尾添加一个按钮,以便每次用户按下此按钮时,您都会再次调用服务器,但是会进入下一页。 然后你将接收到的数据追加到旧的数据中,然后调用collectionView.reloadData。您也可以在没有按钮的情况下执行此操作,仅当用户到达集合视图的末尾时,它才会自动启动。

你可以做第二个这样:

if (CGRectGetMaxY(scrollView.bounds) == scrollView.contentSize.height) { 
    callToServer() 
} 

你可以把它自动的,当附近的集合视图底部的用户滚动,你可以触发要求更多的负载,在全球线程,比准备重新加载您的收藏视图与新的数据。这种方法需要根据您的需求量身定制。这里是伪代码示例(由于问题的标签而迅速):

class VideoList { 
    var dataModel: [SomeDataModelType] 
    var isLoadingMore = false 

    // .. variables and methods 

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { 
     let preloadingTreashold = Int(dataModel.count * 0.75) 
     let threasholdReached = indexPath.item >= preloadingTreashold 
     let reachedLastElement = indexPath.item == dataModel.count - 1 
     if !isLoadingMore { 
     loadMore() 
     } 
    } 

// Example function for load more, a little bit pseudocode. 
// The idea is only to illustrate the case. 
    func loadMore { 
    isLoadingMore = true 

    // distpatch loading on global queue, because we don't 
    // want to block the main thread 
    DispatchQueue.global().async { 
     // if your data model is a class You may need to copy it 
     // before You alter it, because otherwise, a user interaction 
     // can trigger an out of bounds exception or some other kind 
     // of nasty problem 
     var tmpDataModel = dataModel.copy() 

     // load new data model 
     var extendedDataModel = loadMore(to: tmpDataModel) 

     DispatchQueue.main.async { 
     // callback for loaid more completed or reloadData call 
     isLoadingMore = false   
     } 
    } 
    } 

    // other methods ... 
}