我有一个功能来从我的Firebase数据库中获取帖子并使用以下方式一次填充一个集合视图,每次15个帖子:
ref.child("posts").queryOrderedByKey().queryLimited(toLast: 15).observeSingleEvent(of: .value, with: { (snap) in
现在我希望每次用户到达屏幕底部时都会提取下15个帖子。在我的cellForItem
方法中,我正在尝试检查页面的底部是否已到达,如果是,请在下一个帖子中加载。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath) as! PostCell
cell.postImage.loadImageUsingCacheWithUrlString(posts[indexPath.row].pathToImage)
cell.postID = posts[indexPath.row].postID
cell.postImage.contentMode = UIViewContentMode.scaleAspectFill
if indexPath.row == posts.count - 1
{
fetchPosts()
}
return cell
}
我只是不知道如何指定当下一个15个帖子被加载时,他们需要从最后15个帖子开始,而不是再次获取数据库中的所有帖子。
这是整个fetchPosts()
函数:
func fetchPosts() {
let ref = FIRDatabase.database().reference()
ref.child("users").queryOrderedByKey().observe(.value, with: { snapshot in
let users = snapshot.value as! [String : AnyObject]
for (_, value) in users {
if let uid = value["uid"] as? String {
if uid == FIRAuth.auth()?.currentUser?.uid {
if let followingUsers = value["following"] as? [String : String] {
for (_, user) in followingUsers {
self.following.append(user)
}
}
self.following.append(FIRAuth.auth()!.currentUser!.uid)
ref.child("posts").queryOrderedByKey().queryLimited(toLast: 15).observeSingleEvent(of: .value, with: { (snap) in
for postSnapshot in snap.children.allObjects as! [FIRDataSnapshot] {
let value = postSnapshot.value as! [String : AnyObject]
if let userID = value["userID"] as? String {
for each in self.following {
if each == userID {
let posst = Post()
if let poster = value["poster"] as? String, let likes = value["likes"] as? Int, let pathToImage = value["pathToImage"] as? String, let postID = value["postID"] as? String {
posst.poster = poster
posst.likes = likes
posst.pathToImage = pathToImage
posst.postID = postID
posst.userID = userID
if let people = value["peopleWhoLike"] as? [String : AnyObject] {
for (_, person) in people {
posst.peopleWhoLike.append(person as! String)
}
}
posts.append(posst)
}
}
}
self.collectionView.reloadData()
}
}
})
ref.removeAllObservers()
}
}
}
})
}
我可以在此处添加/更改哪些内容以确保每次到达页面底部时按顺序加载15个帖子?
答案 0 :(得分:0)
Haven没试过,但这是个主意。 我会设置两个变量:
let readLimit:Int = 15
var readOffset:Int = 15
第一个变量是硬编码的,代表极限,应该加载新的结果。
在cellForItem
功能中,请检查:
// Check if user scrolled to last row
if (indexPath.item + 1) == readOffset {
// Yes, scrolled to last row
// Increase limit to load more from database
readOffset += readLimit
// Call function which loads data from database
self.fetchPosts()
}
你知道我在哪里吗?现在你必须稍微修改一下read函数:
更改queryLimited(toLast: 15)
:将self替换为self.readOffset
请记住,这还没有经过测试,只是在这里写下来帮助您理解。