Created
May 7, 2019 12:19
-
-
Save tsif/e457231865417c92656ff251f9c5697c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
@objc class CollectionViewLayout: UICollectionViewLayout { | |
var contentSize: CGSize = .zero | |
var cachedAttributes = [IndexPath: UICollectionViewLayoutAttributes]() | |
override func prepare() { | |
// Reset previous | |
contentSize = .zero | |
cachedAttributes = [IndexPath: UICollectionViewLayoutAttributes]() | |
guard let collectionView = collectionView else { | |
return | |
} | |
// Iterate | |
for section in 0 ..< collectionView.numberOfSections { | |
for item in 0 ..< collectionView.numberOfItems(inSection: section) { | |
// ...Determine the frame of your cell... | |
let itemFrame: CGRect = .zero | |
// Set the frame | |
let indexPath = IndexPath(item: item, section: section) | |
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) | |
attributes.frame = itemFrame | |
// Cache | |
cachedAttributes[indexPath] = attributes | |
} | |
} | |
// Store computed content size | |
contentSize = .zero | |
} | |
override var collectionViewContentSize: CGSize { | |
return contentSize | |
} | |
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { | |
var attributeList = [UICollectionViewLayoutAttributes]() | |
for (_, attributes) in cachedAttributes { | |
if attributes.frame.intersects(rect) { | |
attributeList.append(attributes) | |
} | |
} | |
return attributeList | |
} | |
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { | |
return cachedAttributes[indexPath] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment