我正在使用collection View并通过API调用加载更多数据。当我从API加载更多数据时,collectionView在底部显示了活动指示器,但仅在更新现有单元格时无法添加更多collectionView单元格。
任何帮助将不胜感激。
供参考
// MARK: Delegates
extension ProdSubCat: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.row == subCatArr.count - 1 && !self.isLoading {
loadMoreData()
}
}
For load more data
======================
func loadMoreData() {
if !self.isLoading {
self.isLoading = true
DispatchQueue.global().async {
// Fake background loading task for 2 seconds
sleep(2)
// Download more data here
self.productSubCategories(offset: self.offsetValue, limit: 25)
DispatchQueue.main.async {
self.collectionView.reloadData()
self.isLoading = false
}
}
}
}
API CALL Method:
======================
// MARK: API
func productSubCategories(offset: Int, limit: Int) {
if response.response?.statusCode == 200 {
let swiftyJsonVar = JSON(response.result.value!)
print(swiftyJsonVar["message"].string ?? "")
if let category = swiftyJsonVar["product"].arrayObject {
if category.count != 0 {
self.subCatArr = category as! [[String : Any]]
} else {
self.isLoading = true
}
}
self.offsetValue = self.offsetValue + limit
print(self.offsetValue)
self.collectionView.reloadData()
} else {
print("\(String(describing: response.request))")
print("Error")
}
ProgressHUD.dismiss()
}
} else {
self.alertMessage(title: "Connectivity Error!", message: "Please connect to internet")
ProgressHUD.dismiss()
}
}
答案 0 :(得分:1)
您正在用新值(即
)替换当前数据源值self.subCatArr = category as! [[String : Any]]
相反,您需要将数据附加到当前数组。
if let category = swiftyJsonVar["product"].arrayObject {
if category.count != 0 {
for obj in category {
self.subCatArray.append(obj)
}
} else {
self.isLoading = true
}
}