4

我正在制作一个信使应用程序,例如电报,我想实现无限滚动,我JSQMessageViewController用于聊天。

这是无限滚动的代码:

 override func scrollViewDidScroll(scrollView: UIScrollView) {
   if(scrollView.contentOffset.y >= 0.0 && scrollView.contentOffset.y <= 30.0 && loading == true){
        self.loading = false
        self.loadMore()
    }
}

然后我调用这个函数:

func loadMore() {

            //Controllo se nell'array sono presenti altri messaggi
            if ((chatList?.messages.count)!-1) != self.messages.count{
               //
                CATransaction.begin()
                CATransaction.setDisableActions(true)

                let oldBottomOffset = self.collectionView!.contentSize.height - self.collectionView!.contentOffset.y
                UIView.performWithoutAnimation({ () -> Void in


                self.collectionView!.performBatchUpdates({ () -> Void in

                    let idInit = (self.lastMessageId-self.messagePerPage<0) ? 0 : self.lastMessageId-1-self.messagePerPage
                    let idEnd  = self.lastMessageId-1

                    var indexPaths: [NSIndexPath] = []
                    for(var i = 0; i<idEnd-idInit; i++){
                        print("Creo indexpath \(i)")
                        indexPaths.append(NSIndexPath(forItem: i, inSection: 0))
                    }

                    self.collectionView!.insertItemsAtIndexPaths(indexPaths)

                    let msg = self.chatList?.messages
                    var i = idEnd
                    repeat {
                        let mg = msg![i]
                        let messagechat:JSQMessage = JSQMessage(senderId: mg.sender, senderDisplayName: "", date:mg.time, text: mg.message)
                        messagechat.xmppMessageID = mg.messageID
                        messagechat.status        = mg.messageStatus
                        self.messages.insert(messagechat, atIndex: 0)
                        self.lastMessageId = i
                        i--
                    } while i > idInit

                    // invalidate layout
                    self.collectionView!.collectionViewLayout.invalidateLayoutWithContext(JSQMessagesCollectionViewFlowLayoutInvalidationContext())

                    }, completion: {(finished) in

                        //scroll back to current position
                        self.finishReceivingMessageAnimated(false)
                        self.collectionView!.layoutIfNeeded()
                        self.collectionView!.contentOffset = CGPointMake(0, self.collectionView!.contentSize.height - oldBottomOffset)
                        CATransaction.commit()


                })
                     })
            }
            else {

                print("No more messages to load.")
            }


}

一切正常,但scrolling滚动停止 1 秒。我想是CATransaction这样做的,有时我会看到跳转效果,如果我添加 10 条新消息,我会在第一时间看到 10 条消息中的第一条消息,然后将偏移量正确设置为旧位置。我怎样才能解决这个问题?我看到电报scrolling很完美,加载旧消息时没有跳转效果。

4

0 回答 0