随着新内容的推出,滚动到底部

时间:2018-04-24 01:34:18

标签: ios swift uicollectionview

所以我在我的应用中有UICollectionView类似的聊天功能。当用户发送新消息时,他们会通过观察者模式进入应用程序。但是当新内容出现时。它最终低于keyboard并且永远不会自我调整。当我切换keyboard时,我有一个这样的功能,似乎可以实现这个目标。但是,当我在我的completion handler中尝试类似的代码时,它会失败并给我这条消息。

  

' NSInvalidArgumentException',原因:'尝试滚动到无效索引路径:{length = 2,path = 0 - 9}'   ***首先抛出调用堆栈:

fileprivate func tryObserveComments(){
    print(eventKey)
    commentHandle = ChatService.observeMessages(forChatKey: eventKey) { (ref, newComments) in
        self.commentRer = ref
        self.comments.append(newComments!)
        self.adapter.performUpdates(animated: true)
        let item = self.collectionView.numberOfItems(inSection: self.collectionView.numberOfSections - 1) - 1
        let insertionIndexPath = IndexPath(item: item, section: self.collectionView.numberOfSections - 1)
        self.collectionView.scrollToItem(at: insertionIndexPath, at: UICollectionViewScrollPosition.top, animated: true)
    }
}

出于某种原因,在奇怪的情况下,它确实有效。一些keyboard部分覆盖了细胞

1 个答案:

答案 0 :(得分:0)

尝试使用performBatchUpdates,我认为它将在您排除

时起作用
 fileprivate func tryObserveComments(){
    print(eventKey)
    commentHandle = ChatService.observeMessages(forChatKey: eventKey) { (ref, newComments) in
        self.commentRer = ref
        self.comments.append(newComments!)
        self.adapter.performUpdates(animated: true)
        self.collectionView.performBatchUpdates({
        let item = self.collectionView.numberOfItems(inSection: self.collectionView.numberOfSections - 1) - 1
        let insertionIndexPath = IndexPath(item: item, section: self.collectionView.numberOfSections - 1)
        }, completion: { (Bool) in
            self.collectionView.scrollToItem(at: insertionIndexPath, at: UICollectionViewScrollPosition.top, animated: true)
        })
    }
 }