Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Created February 23, 2021 03:06
Show Gist options
  • Save Koshimizu-Takehito/33b1275a7eba0cdc1cf172e6f7257eaf to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/33b1275a7eba0cdc1cf172e6f7257eaf to your computer and use it in GitHub Desktop.
UICollectionViewでタグが左寄せに並んでいるようなレイアウトを実現する
class FlowLayoutHorizontalLeft: UICollectionViewFlowLayout {
private var cache: [IndexPath: UICollectionViewLayoutAttributes] = [:]
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
super.layoutAttributesForElements(in: rect)?
.lazy
.filter { $0.representedElementCategory == .cell }
.map { self.layoutAttributesForItem(at: $0.indexPath) }
.compactMap { $0 }
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let current = super.layoutAttributesForItem(at: indexPath)
let previous = cache[IndexPath(item: indexPath.item - 1, section: indexPath.section)]
switch (current, previous) {
case let (current?, previous?) where current.center.y == previous.center.y:
current.center.x = (previous.center.x - previous.bounds.midX + previous.bounds.width)
+ current.bounds.midX + minimumInteritemSpacing
cache[indexPath] = current
return current
case let (current, _):
cache[indexPath] = current
return current
}
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
let shouldInvalidate = super.shouldInvalidateLayout(forBoundsChange: newBounds)
if shouldInvalidate {
cache.removeAll(keepingCapacity: true)
}
return shouldInvalidate
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment