Skip to content

Instantly share code, notes, and snippets.

@joey-barbier
Last active August 3, 2017 12:07
Show Gist options
  • Save joey-barbier/13ef56ed5885d3c6fd284b6fb0fbc50e to your computer and use it in GitHub Desktop.
Save joey-barbier/13ef56ed5885d3c6fd284b6fb0fbc50e to your computer and use it in GitHub Desktop.
Append data in a CollectionView from an API - Swift v3
func collectionView(_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
//construct your cell :
guard let cell = cell as? CustomCollectionViewCell else {
return
}
guard let item = data?[indexPath.item] else {
return
}
cell.item = item
// - check if item showed is a last of your array -
if let data = data, item === data.last {
//call API with offset (data.count+1)
API.request.nextPage?("\(data.count+1)", { dataReceipt in
guard let data = self.data, let dataReceipt = dataReceipt else {
return
}
var newIndexPath = [IndexPath]()
let firstNewIndex = indexPath.item+1
//create new index path
for i in firstNewIndex...(firstNewIndex+dataReceipt.count-1) {
newIndexPath.append(IndexPath(item: i, section: 0))
}
//concatenating your data
self.data = data + dataReceipt
// inform collection view for she adding the new cells
self.collectionView.performBatchUpdates({
self.collectionView.insertItems(at: newIndexPath)
}, completion: nil)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment