I have a function:
// Cant pass it directly into the init because it is an override init :/
override init() {
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
weak var delegate: layoutDelegate?
private var cache: [UICollectionViewLayoutAttributes] = []
private var contentHeight: CGFloat = 0
private var contentWidth: CGFloat {
guard let collectionView = collectionView else {
print("Collectionview not found")
return 0
}
let insets = collectionView.contentInset
return collectionView.bounds.width - (insets.left + insets.right)
}
override var collectionViewContentSize: CGSize {
return CGSize(width: contentWidth, height: contentHeight)
}
override func prepare() {
guard
cache.isEmpty,
let collectionView = collectionView
else { print("No Collectionview rip"); return }
let columnWidth = contentWidth
for item in 0..<collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let postHeight = delegate?.collectionView(_collectionView: collectionView, heightForPostAtIndexPath: indexPath) ?? 200
let height = postHeight
let frame = CGRect(x: 0, y: 0, width: columnWidth, height: height)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
cache.append(attributes)
contentHeight = max(contentHeight, frame.maxY)
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleLayoutAttributes: [UICollectionViewLayoutAttributes] = []
// Loop through the cache and look for items in the rect
for attributes in cache {
if attributes.frame.intersects(rect) {
visibleLayoutAttributes.append(attributes)
}
}
return visibleLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath.item]
}
}
I have my own collectionView called CustomCollectionView and I want to pass it into this function to use instead of the default collectionView
that this function gives me because it is of type UICollectionViewLayout
. However I am unsure how I am supposed to pass in my own collectionView because this function is using an override init()
and I am not able to pass variables into it.
Question:
How do I pass a variable into this class so that I can use my customCollectionView
instead of the default collectionView