简体   繁体   English

Swift 中特定部分的 UICollectionView 粘性标题

[英]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 .到目前为止我找到的解决方案一直工作到900 collectionView.contentOffset.y I followed with this code StickyLayout.swift .我跟着这个代码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.而且我必须设置sectionHeadersPinToVisibleBounds = false因为我只想在顶部粘贴一个标题,同时根据位置向上/向下滚动。 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.因为我是在 Swift 中做这件事的,所以在 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.当您在 for 循环中迭代时,这会导致标题的布局属性不包含在属性数组中,从而导致布局位置不再调整到屏幕顶部的“粘性”位置。

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:在 for 循环之前添加这些行以将粘性标题的布局属性添加到属性数组(如果它们不存在):

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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