Last active
November 16, 2023 13:24
-
-
Save 50percentgrey/4cacac3760e39a63fcedc9fd6ce8990a to your computer and use it in GitHub Desktop.
Self-sizing CollectionView/Cell
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
// setup your collectionView | |
private let collectionView: UICollectionView = { | |
let layout = UICollectionViewFlowLayout() | |
layout.scrollDirection = .horizontal | |
layout.minimumInteritemSpacing = 20.0 | |
layout.minimumLineSpacing = 20.0 | |
// important! | |
layout.itemSize = UICollectionViewFlowLayout.automaticSize | |
// change estimatedItemSize for a vertical example | |
layout.estimatedItemSize = CGSize(width: UIScreen.main.bounds.width, height: 40.0) | |
// collectionView | |
let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) | |
view.translatesAutoresizingMaskIntoConstraints = false | |
view.contentInset = UIEdgeInsets.zero | |
view.decelerationRate = .fast | |
return view | |
}() | |
// you just need the basic stuff | |
//MARK: - CollectionView - | |
extension YourViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { | |
func collectionView( | |
_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { | |
return dataSource.count | |
} | |
func collectionView( | |
_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { | |
let data = dataSource[indexPath.row] | |
return configureItemCell(indexPath: indexPath, data: data) | |
} | |
} | |
/** | |
CollectionViewCell | |
*/ | |
final class ItemCell: UICollectionViewCell { | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
layout() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { | |
layoutIfNeeded() | |
let size = systemLayoutSizeFitting(layoutAttributes.size) | |
let frame = CGRect(origin: layoutAttributes.frame.origin, size: CGSize(width: size.width, height: size.height)) | |
layoutAttributes.frame = frame | |
return layoutAttributes | |
} | |
} |
Hi Antonio!
Code is perfect for sample cells without headers.
But I have a strange bug on iPhone 6S (iOS 15.8), headers overlapping:
when the user clicks on the first header, the second header does not move down after the last cell of the first header.
Have you met this bug before?
P.S.
This bug appears on iPhone 6S (iOS 15.8) only
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what is this layout() in override init(frame: CGRect) { method ?