如何只刷新或重新加载collectionview或tableview中新添加的数据,而不是重新加载所有数据?现在我正在使用以下代码,但它查询数据库服务器以获取所有数据然后重新加载所有内容。例如,我只在服务器上上传一张照片,所以我只想获取该照片并仅为这张新添加的照片重新加载 collectionview,而不是加载所有内容。我怎样才能做到这一点?谢谢!
func loadPosts(){
let query = PFQuery(className: "posts")
query.whereKey("username", equalTo:PFUser.current()!.username!)
query.limit = page
query.findObjectsInBackground { (objects, error) in
if error == nil {
self.picArray.removeAll(keepingCapacity: false)
if let objects = objects{
for object in objects{
self.picArray.append(object.value(forKey: "pic") as! PFFile)
}
}
self.collectionView?.reloadData()
} else{
print(error!.localizedDescription)
}
}
}
Collection View 函数
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return picArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//define cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! pictureCell
picArray[indexPath.row].getDataInBackground { (data, error) in
if error == nil {
cell.picImg.image = UIImage(data: data!)
} else {
print(error!.localizedDescription)
}
}
return cell
}
最佳答案
最终我会建议将图像请求从 cellForItem
中移出,因为根据用户的滚动行为,它会被调用很多次,但目前这会起作用。
您需要检查图像是否已经加载然后使用 reloadItems
而不是 reloadData
这样您在 cellForItem
中的新部分将看起来像这样的东西:
if (cell.picImg.image == nil) {
picArray[indexPath.row].getDataInBackground { (data, error) in
if error == nil {
cell.picImg.image = UIImage(data: data!)
collectionView.reloadItems(at: indexPath) //reload only this item once the image is retrieved
} else {
print(error!.localizedDescription)
}
}
}
关于ios - 如何刷新collectionview或tableview中的数据只为更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49465764/