binarySearchAttributes(range: , rect: ),这个方法是怎么实现的?

WWDC2018 Session225 中提到继承 UICollectionViewLayout 自定义了一个 MosaicLayout 类,MosaicLayout 类在

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?

中使用了二分查找来优化展示效率,其中有一个方法

// 找到在当前区域内的任何一个 Attributes 的 Index
let firstMatchIndex = binarySearchAttributes(range: , rect:)

请问这个 binarySearchAttributes(range: , rect:) 应该如何实现?
MosaicLayout.swift 代码如下

import UIKit

class MosaicLayout: UICollectionViewLayout {

    var contentBounds = CGRect.zero
    var cachedAttributes = [UICollectionViewLayoutAttributes]()

    override func prepare() {
        super.prepare()
        guard let cv = collectionView else { return }
        cachedAttributes.removeAll()
        contentBounds = CGRect(origin: .zero, size: cv.bounds.size)
    }

    override var collectionViewContentSize: CGSize {
        return contentBounds.size
    }

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        guard let cv = collectionView else {
            return false
        }
        return !newBounds.size.equalTo(cv.bounds.size)
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return cachedAttributes[indexPath.item]
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var attributesArray = [UICollectionViewLayoutAttributes]()
        guard let firstMatchIndex = binarySearchAttributes(range: 0...cachedAttributes.endIndex, rect:rect) else { return attributesArray }    
    }
}

报错信息如下

clipboard.png

阅读 1.2k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题