UICollectionView刷新:多次获取每个单元格



嗨,我有一个问题,在刷新我的collectionView后,我在我的观点。第二次刷新后,我会对每个单元格进行3次刷新。我在第二次用segue介绍这个观点时也遇到了这个问题。

我该怎么解决?

有人能帮我吗?

提前感谢


import UIKit
import Firebase

class FeedViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private let refreshControl = UIRefreshControl()
@IBOutlet weak var collectionview: UICollectionView!
var posts = [Post]()

override func viewDidLoad() {
super.viewDidLoad()
collectionview.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(refreshWeatherData(_:)), for: .valueChanged)
refreshControl.tintColor = UIColor(hex: "#F17D32")

}

@objc private func refreshData(_ sender: Any) {
fetchData()
posts.removeAll()
collectionview.reloadData()
}
private func fetchData() {
getPost()
self.refreshControl.endRefreshing()

}

func getPosts(){
let ref = Database.database().reference()
ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snap) in

let postsSnap = snap.value as! [String : AnyObject]
for (_,post) in postsSnap {

let posst = Post()
if let author = post["author"] as? String, late date = post["date"], let postID = post["postID"] as? String, let userID = post["userID"] as? String  {
posst.date = date
posst.author = author
posst.postID = postID
posst.userID = userID
self.posts.sort(by: {$0.postdateprog > $1.postdateprog})
self.posts.append(posst)
}

self.collectionview.reloadData()
}
})

}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(posts.count)
return self.posts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath) as! PostCell
cell.authorlabel.text = self.posts[indexPath.row].author
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: self.collectionview.frame.width / 2 - 20, height: self.collectionview.frame.width * 0.7)
}
}

Firebase函数是异步的,在同步代码运行后将调用闭包中的代码。换句话说,你有这个

fetchData()
posts.removeAll()
collectionview.reloadData()

但是CCD_ 1和CCD_。

因此,这里有一个截断的概述,概述了调用事物的顺序。

@objc private func refreshData(_ sender: Any) {
self.loadFirebaseData()
}
func loadFirebaseData() {
...
self.posts = []
for (_,post) in postsSnap {
self.posts.append(posst)
}
self.posts.sort(by: {$0.postdateprog > $1.postdateprog}
self.collectionview.reloadData()
}

请注意,我将排序和reloadData移到了for循环之外。在填充数据源时,没有理由反复调用这些函数。任务完成后再做。

最新更新