I'm trying to make collectionView with CompositionalLayout, and make certain cell always stay sticky to the top whether the other section appears or not. Here is my code customizing UICollectionViewLayout
public final class StickyCollectionViewCompositionalLayout: UICollectionViewCompositionalLayout {
var stickyIndexPath: IndexPath? {
didSet {
invalidateLayout()
}
}
init(
stickyIndexPath: IndexPath?,
configuration: UICollectionViewCompositionalLayoutConfiguration,
sectionProvider: @escaping UICollectionViewCompositionalLayoutSectionProvider
) {
self.stickyIndexPath = stickyIndexPath
super.init(sectionProvider: sectionProvider, configuration: configuration)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 스크롤 할 때마다 layout 재설정
public override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
public override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = super.layoutAttributesForElements(in: rect)
if let stickyAttributes = getStickyAttributes(at: stickyIndexPath) {
layoutAttributes?.append(stickyAttributes)
}
return layoutAttributes
}
private func getStickyAttributes(at indexPath: IndexPath?) -> UICollectionViewLayoutAttributes? {
guard
let collectionView = self.collectionView,
let indexPath = indexPath,
let stickyAttributes = layoutAttributesForItem(at: indexPath)?.copy()
as? UICollectionViewLayoutAttributes
else {
return nil
}
if collectionView.contentOffset.y > stickyAttributes.frame.minY {
var frame = stickyAttributes.frame
frame.origin.y = collectionView.contentOffset.y
stickyAttributes.frame = frame
stickyAttributes.zIndex = 9
stickyAttributes.isHidden = false
return stickyAttributes
}
return nil
}
}
if there is no section with orthgonalScrollingBehavior in collectionView, it works perfectly but with orthgonalScrollingBehavior, the sticky cell disappears when scrolled.
Is there any solution?
tried customizing UICollectionViewLayout