当前视图控制器上最后一项UICollectionView

问题描述:

我正在做一个简单的聊天应用程序,所以当用户点击聊天列表中的特定聊天时,他必须去这个特定聊天室中的最后一条消息(如电报)。 我试图创建自己的scrollToBottom功能:当前视图控制器上最后一项UICollectionView

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中调用它,我得到小的延迟就跳转到聊天室,这是不好的最后一行之前。请帮忙!

+0

多少消息是你获取/从DB显示在一旦? –

+0

试试这个[self.collectionView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:finalRow inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES]; – Avaan

+0

the_UB,取决于,大约50-100条消息 –

viewWillAppear将在viewDidLoad之后调用。如果您的viewcontroller启动后需要调用此方法,则可以在viewDidload方法中添加代码。 但是如果你仍然需要使用viewWillAppear,我建议将这个调用包装在主线程或mainqueue上。您可以使用GCD或NSOperationQueue。

我想,这可能会在延迟问题,帮助

如果聊天消息在UITableView渲染,使用函数

self.tableView scrollToRowAtIndexPath:<#(nonnull NSIndexPath *)#> atScrollPosition:<#(UITableViewScrollPosition)#> animated:<#(BOOL)#> 

这种方法将运动与良好的动漫内容。

感谢@Sabby,我将此代码添加到viewWillAppear中,并以某种方式它的工作

let delayTime = dispatch_time(DISPATCH_TIME_NOW, 0) 
    dispatch_after(delayTime,dispatch_get_main_queue()) { 
     self.collectionView.contentInset.bottom = 40.0 
     self.scrollToBottom(animated: false) 
    } 
+0

Cheers @pavel_s – Sabby