简体   繁体   中英

UICollectionView sticky header for specific section in Swift

I'm trying to create a sticky supplementary header for a specific section, which stays on top all the time when the specific section touches on the navigation and won't overlay with other section headers. The solutions I found so far is working till 900 collectionView.contentOffset.y . I followed with this code StickyLayout.swift .

And I have to set sectionHeadersPinToVisibleBounds = false because I want to stick only one header on top while scrolling up/down depending on the position. Other section headers should not push out the sticky header.

As I'm doing this in Swift, it would be great to have an example in Swift.

This caused the header's layout attribute to not be included in the attributes array when you iterated over in the for loop, resulting in the layout position no longer being adjusted to its "sticky" position at the top of the screen.

Adding these lines right before the for loop to add the sticky header's layout attributes to the attributes array if they are not there:

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var layoutAttributes = [UICollectionViewLayoutAttributes]()

    guard let cellLayoutAttributesInRect = super.layoutAttributesForElements(in: rect) else { return nil }

    // add the sticky header's layout attribute to the attributes array if they are not there
    if let stickyHeaderIndexPath = stickyHeaderIndexPath,
        let stickyAttribute = layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: stickyHeaderIndexPath),
        !layoutAttributes.contains(stickyAttribute) {
        layoutAttributes.append(stickyAttribute)
    }

    return layoutAttributes
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM