我正在制作简单的聊天应用程序,因此当用户点击聊天列表中的特定聊天时,他必须转到该特定聊天室中的最后一条消息(例如在 Telegram 中)。我试图创建自己的 scrollToBottom 函数:
func scrollToBottom(animated animated: Bool) {
if self.collectionView.numberOfSections() == 0 {
return
}
if self.collectionView.numberOfItemsInSection(0) == 0 {
return
}
let collectionViewContentHeight = self.collectionView.collectionViewLayout.collectionViewContentSize().height
let isContentTooSmall = collectionViewContentHeight < CGRectGetHeight(self.collectionView.bounds)
if isContentTooSmall {
self.collectionView.scrollRectToVisible(CGRectMake(0, collectionViewContentHeight - 1, 1, 1), animated: animated)
return
}
let finalRow = max(0, self.collectionView.numberOfItemsInSection(0) - 1)
let finalIndexPath = NSIndexPath(forRow: finalRow, inSection: 0)
let finalCellSize = self.collectionView.messagesCollectionViewLayout.sizeForItem(finalIndexPath)
let maxHeightForVisibleMessage = self.collectionView.bounds.height - self.collectionView.contentInset.top
let scrollPosition: UICollectionViewScrollPosition = finalCellSize.height > maxHeightForVisibleMessage ? .Bottom : .Top
self.collectionView.scrollToItemAtIndexPath(finalIndexPath, atScrollPosition: scrollPosition, animated: animated)
}
但是当我在 viewWillAppear 中调用它时,我会在它跳到聊天室的最后一行之前得到一点延迟,这并不好。请帮忙!