UICollectionView不会在前几个项目上滚动到底部

时间:2016-10-20 06:59:30

标签: ios iphone swift uicollectionview ios10

我一直在尝试创建一个可以重复使用的聊天界面。我差不多完成了实现,但有些事情让我不禁烦恼。如果我在第一次加载界面时开始加载像gif这样的消息,你可以看到在第4条消息之后有3条消息没有滚动到底部。第8个是第一个最终滚动的。这取决于屏幕尺寸。在iPhone 6s测试设备上,它到达第9条消息,即滚动的消息。

我正在使用内容插入作为保持集合视图可见的方法,每次底部的UIToolbar框架更改时都会运行以下代码

toolBar.inputAccessoryViewFrameChanged = {(rect: CGRect) in Void()
    let navigationAndStatusHeight = self.navigationController != nil && self.navigationController!.navigationBar.isTranslucent ? self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.height : 0
    self.collectionView.contentInset = UIEdgeInsets(top: navigationAndStatusHeight + 8, left: 8, bottom: UIScreen.main.bounds.height - rect.origin.y + 8, right: 8)
    self.collectionView.scrollIndicatorInsets.bottom = UIScreen.main.bounds.height - rect.origin.y
}

每次插入新邮件时都会运行此代码:

func insertNewMessage(){
    self.collectionView.performBatchUpdates({
        self.collectionView.insertItems(at: [NSIndexPath(item: self.numberOfMessages() - 1, section: 0) as IndexPath])
        }) { (Bool) in
        self.scrollToBottom(animated: true)
    }
}

使用scrollToBottom函数:

func scrollToBottom(animated: Bool){
    guard self.numberOfMessages() > 0 else{
        return
    }
    self.collectionView.scrollToItem(at: IndexPath(item: self.numberOfMessages() - 1, section: 0), at: UICollectionViewScrollPosition.top , animated: animated)  
}

我目前正在运行此版本的XCode版本8.1 beta(8T29o)& iOS 10.1(14B55c)

1 个答案:

答案 0 :(得分:6)

问题可能是当集合视图内容大小太小时,scrollToItem无法正常工作。尝试使用此代码

func scrollToBottomAnimated(animated: Bool) {
        guard self.collectionView.numberOfSections > 0 else{
            return
        }

        let items = self.collectionView.numberOfItems(inSection: 0)
        if items == 0 { return }

        let collectionViewContentHeight = self.collectionView.collectionViewLayout.collectionViewContentSize.height
        let isContentTooSmall: Bool = (collectionViewContentHeight < self.collectionView.bounds.size.height)

        if isContentTooSmall {
            self.collectionView.scrollRectToVisible(CGRect(x: 0, y: collectionViewContentHeight - 1, width: 1, height: 1), animated: animated)
            return
        }

        self.collectionView.scrollToItem(at: NSIndexPath(item: items - 1, section: 0) as IndexPath, at: .bottom, animated: animated)

    }