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 }
}
}
报错信息如下