2017-03-05 50 views
1

我有一個支持分頁的api。如何加載更多的collectionview?

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

我的目標是將nextPageUrl的圖像添加到我的collectionview。 那麼我該如何做到這一點?

任何建議或代碼示例?我是swift新手。非常感謝:)

回答

1

您需要在集合視圖的末尾添加一個按鈕,以便每次用戶按下此按鈕時,您都會再次調用服務器,但是會進入下一頁。 然後你將接收到的數據追加到舊的數據中,然後調用collectionView.reloadData。您也可以在沒有按鈕的情況下執行此操作,僅當用戶到達集合視圖的末尾時,它纔會自動啓動。

你可以做第二個這樣:

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

你可以把它自動的,當附近的集合視圖底部的用戶滾動,你可以觸發要求更多的負載,在全球線程,比準備重新加載您的收藏視圖與新的數據。這種方法需要根據您的需求量身定製。這裏是僞代碼示例(由於問題的標籤而迅速):

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 ... 
} 
相關問題