ios - 如何刷新collectionview或tableview中的数据只为更新?

标签 ios swift uicollectionview

如何只刷新或重新加载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/

相关文章:

swift - bar Items 中的导航链接返回到 NavigationView 的顶部

ios - 强制触摸 UITableViewCell 内部的 UICollectionView

ios - 滚动单元格时 UIcollectionview 滞后

swift - UICollectionView 视频性能

ios - 该 View 是 Iphone XS Max、Iphone 11 pro max 上的显示差异以及差异项目

objective-c - 收到推送通知时如何调用函数?

ios - 如何在 swift iOS 应用程序中创建简单的播放器

ios - 只有第一个 collectionViewCell 对用户交互使用react

ios - NSURLConnection 完成时出现错误 1200,现在是 1202?

ios - 连接表 parse.com