滚动具有大量单元格(250,000 或更多)的两种方式滚动 UICollectionView 时可见滞后

Visible lag while scrolling two way scrolling UICollectionView with large number of cells (250,000 or more)

我正在对 UICollectionViewFlowLayout 进行子类化,以便在 UICollectionView 中实现双向滚动。对于较少数量的行和节数(100-200 行和节),滚动效果很好,但是当我将行和节数增加超过 500,即 UICollectionView 中的 250,000 或更多单元格时,滚动时会出现明显的滞后。我已经追踪到 layoutAttributesForElementsInRect 中的循环中的延迟源。我正在使用 Dictionary 来保存每个单元格的 UICollectionViewLayoutAttributes 以避免重新计算它并将其循环到 layoutAttributesForElementsInRect

中单元格的 return 属性
import UIKit

class LuckGameCollectionViewLayout: UICollectionViewFlowLayout {

    // Used for calculating each cells CGRect on screen.
    // CGRect will define the Origin and Size of the cell.
    let CELL_HEIGHT = 70.0
    let CELL_WIDTH = 70.0

    // Dictionary to hold the UICollectionViewLayoutAttributes for
    // each cell. The layout attribtues will define the cell's size
    // and position (x, y, and z index). I have found this process
    // to be one of the heavier parts of the layout. I recommend
    // holding onto this data after it has been calculated in either
    // a dictionary or data store of some kind for a smooth performance.
    var cellAttrsDictionary = Dictionary<NSIndexPath, UICollectionViewLayoutAttributes>()
    // Defines the size of the area the user can move around in
    // within the collection view.
    var contentSize = CGSize.zero

    override func collectionViewContentSize() -> CGSize {
        return self.contentSize
    }

    override func prepareLayout() {

        // Cycle through each section of the data source.
        if collectionView?.numberOfSections() > 0 {
            for section in 0...collectionView!.numberOfSections()-1 {

                // Cycle through each item in the section.
                if collectionView?.numberOfItemsInSection(section) > 0 {
                    for item in 0...collectionView!.numberOfItemsInSection(section)-1 {

                        // Build the UICollectionVieLayoutAttributes for the cell.
                        let cellIndex = NSIndexPath(forItem: item, inSection: section)
                        let xPos = Double(item) * CELL_WIDTH
                        let yPos = Double(section) * CELL_HEIGHT

                        let cellAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: cellIndex)
                        cellAttributes.frame = CGRect(x: xPos, y: yPos, width: CELL_WIDTH, height: CELL_HEIGHT)

                        // Save the attributes.
                        cellAttrsDictionary[cellIndex] = cellAttributes
                    }
                }

            }
        }

        // Update content size.
        let contentWidth = Double(collectionView!.numberOfItemsInSection(0)) * CELL_WIDTH
        let contentHeight = Double(collectionView!.numberOfSections()) * CELL_HEIGHT
        self.contentSize = CGSize(width: contentWidth, height: contentHeight)

    }

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        // Create an array to hold all elements found in our current view.
        var attributesInRect = [UICollectionViewLayoutAttributes]()

        // Check each element to see if it should be returned.
        for (_,cellAttributes) in cellAttrsDictionary {
            if CGRectIntersectsRect(rect, cellAttributes.frame) {
                attributesInRect.append(cellAttributes)
            }
        }

        // Return list of elements.
        return attributesInRect
    }

    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
        return cellAttrsDictionary[indexPath]!
    }

    override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
        return false
    }
}

编辑: 以下是我在 layoutAttributesForElementsInRect 方法中提出的更改。

override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {        
    // Create an array to hold all elements found in our current view.
    var attributesInRect = [UICollectionViewLayoutAttributes]()

    let xOffSet = self.collectionView?.contentOffset.x
    let yOffSet = self.collectionView?.contentOffset.y
    let totalColumnCount = self.collectionView?.numberOfSections()
    let totalRowCount = self.collectionView?.numberOfItemsInSection(0)

    let startRow = Int(Double(xOffSet!)/CELL_WIDTH) - 10    //include 10 rows towards left
    let endRow = Int(Double(xOffSet!)/CELL_WIDTH + Double(Utils.getScreenWidth())/CELL_WIDTH) + 10 //include 10 rows towards right
    let startCol = Int(Double(yOffSet!)/CELL_HEIGHT) - 10 //include 10 rows towards top
    let endCol = Int(Double(yOffSet!)/CELL_HEIGHT + Double(Utils.getScreenHeight())/CELL_HEIGHT) + 10 //include 10 rows towards bottom

    for(var i = startRow ; i <= endRow; i = i + 1){
        for (var j = startCol ; j <= endCol; j = j + 1){
            if (i < 0 || i > (totalRowCount! - 1) || j < 0 || j > (totalColumnCount! - 1)){
                continue
            }

            let indexPath: NSIndexPath = NSIndexPath(forRow: i, inSection: j)
            attributesInRect.append(cellAttrsDictionary[indexPath]!)
        }
    }

    // Return list of elements.
    return attributesInRect
}

我已经计算了 collectionView 的偏移量并用它来计算将在屏幕上可见的单元格(使用每个单元格的 height/width)。我不得不在每一侧添加额外的单元格,这样当用户滚动时就不会丢失单元格。我已经测试过了,性能很好。

您需要为您的单元格提出一个按维度排序的数据结构,以便提出一些使用这些维度的算法来缩小搜索范围。

让我们以 table 的情况为例,单元格高 100 像素,占视图的整个宽度,并且 250_000 元素要求单元格与 { 0, top, 320, bottom }.那么你的数据结构将是一个按顶部坐标排序的数组,伴随的算法就像

let start: Int = top / 100
let end: Int = bottom / 100 + 1
return (start...end).map { cellAttributes[[=10=]] }

根据您的实际布局添加尽可能多的复杂性。

cellAttrsDictionary不适合存放UICollectionViewLayoutAttributes。它由 NSIndexPath 索引,但在 layoutAttributesForElementsInRect 中您正在搜索一个区域。如果您需要 cellAttrsDictionary 其他东西,那么您可以保留它,但将每个 cellAttribute 额外地 存储在另一个搜索速度更快的数据结构中。

例如嵌套数组:

var allCellAttributes = [[UICollectionViewLayoutAttributes]]()

第一级数组描述一个区域,假设它是 1000 像素高和全屏宽度的块。所以所有与矩形 { 0, 0, screenwidth, 1000 } 相交的 cellAttributes 进入:

allCellAttributes[0].append(cellAttributes)

与矩形 { 0, 1000, screenwidth, 2000 } 相交的所有 cellAttributes 进入:

allCellAttributes[1].append(cellAttributes)

等等...

然后,在 layoutAttributesForElementsInRect 中,您可以根据给定的 CGRect 直接跳转到数组中来搜索此数据结构。如果矩形是例如{0, 5500, 100, 6700} 那么你只需要在这个范围内搜索:

allCellAttributes[5]
allCellAttributes[6]

这应该给了你基本的思路,希望你明白我的意思。

通过利用已知单元格大小的 layoutAttributesForElementsInRect(rect: CGRect),您无需缓存属性,只需在 collectionView 请求它们时为给定的 rect 计算它们。您仍然需要检查 0 的边界情况和最大 section/row 计数以避免计算不需要或无效的属性,但这可以在循环周围的 where 子句中轻松完成。这是一个我用 1000 个部分 x 1000 行测试过的工作示例,它工作正常,不会在设备上滞后:

编辑:我添加了 biggerRect,以便在滚动到达之前可以预先计算属性。从您的编辑来看,您似乎仍在缓存我认为性能不需要的属性。此外,滚动次数越多,内存占用量也会越大。还有一个原因是您不想使用回调中提供的 CGRect 而不是手动从 contentOffset 中计算一个吗?

class LuckGameCollectionViewLayout: UICollectionViewFlowLayout {

let CELL_HEIGHT = 50.0
let CELL_WIDTH = 50.0

override func collectionViewContentSize() -> CGSize {
    let contentWidth = Double(collectionView!.numberOfItemsInSection(0)) * CELL_WIDTH
    let contentHeight = Double(collectionView!.numberOfSections()) * CELL_HEIGHT
    return CGSize(width: contentWidth, height: contentHeight)
}

override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    let biggerRect = rect.insetBy(dx: -2048, dy: -2048)
    let startIndexY = Int(Double(biggerRect.origin.y) / CELL_HEIGHT)
    let startIndexX = Int(Double(biggerRect.origin.x) / CELL_WIDTH)
    let numberOfVisibleCellsInRectY = Int(Double(biggerRect.height) / CELL_HEIGHT) + startIndexY
    let numberOfVisibleCellsInRectX = Int(Double(biggerRect.width) / CELL_WIDTH) + startIndexX
    var attributes: [UICollectionViewLayoutAttributes] = []

    for section in startIndexY..<numberOfVisibleCellsInRectY
        where section >= 0 && section < self.collectionView!.numberOfSections() {
            for item in startIndexX..<numberOfVisibleCellsInRectX
                where item >= 0 && item < self.collectionView!.numberOfItemsInSection(section) {
                    let cellIndex = NSIndexPath(forItem: item, inSection: section)
                    if let attrs = self.layoutAttributesForItemAtIndexPath(cellIndex) {
                        attributes.append(attrs)
                    }
            }
    }
    return attributes
}

override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
    let xPos = Double(indexPath.row) * CELL_WIDTH
    let yPos = Double(indexPath.section) * CELL_HEIGHT
    let cellAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
    cellAttributes.frame = CGRect(x: xPos, y: yPos, width: CELL_WIDTH, height: CELL_HEIGHT)
    return cellAttributes
}
}