首页 > 解决方案 > 分页时collectionView contentOffset发生变化 - swift - 以编程方式

问题描述

我正在使用 collectionView 构建聊天功能,这样做我正在实现分页:

但是,每当我向模型数组添加更多消息并重新加载 collectionView 数据时collectionView.reloadData(),内容偏移量不受尊重,它会直接跳到顶部。

这是获取更多数据并将其加载到 collectionView 中的代码:

fileprivate func fetchMoreMessages(){
    
    let db = Firestore.firestore()
    
    db.collection("Messages").document(currentUserUid!).collection(chatUserUid!).order(by: "timestamp", descending: false).end(beforeDocument: firstDocumentSnapshot!).limit(to: 20).getDocuments { [self] (snapshot, error) in
        if let error = error{
            print("error in retrieving docs", error.localizedDescription)
            return
        }
        
        let firstDoc = snapshot?.documents.first
        self.firstDocumentSnapshot = firstDoc

        var arrayOfDocuments : [MessageModel] = []
        snapshot?.documents.forEach({ (snapshot) in
            let dict = snapshot.data()
            var message = MessageModel()
            message.initiateMessageWith(dict: dict)
            arrayOfDocuments.append(message)
        })
        self.listOfMessages.insert(contentsOf: arrayOfDocuments, at: 0)
        self.collectionView.reloadData()
    }
}

并在发生这种情况时被调用:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y <= 100{
        if self.isPaginating == false && ((firstDocumentSnapshot?.exists) != nil){
            fetchMoreMessages()
            self.isPaginating = true
        }
    }
}

标签: swiftuicollectionviewcollectionviewreloaddata

解决方案


推荐阅读