【问题标题】:Custom CollectionView header disappears during scroll (Custom UICollectionFlowLayout)自定义 CollectionView 标题在滚动期间消失(自定义 UICollectionFlowLayout)
【发布时间】:2020-04-01 16:06:40
【问题描述】:

我正在制作自定义 UICollectionViewFlowLayout,并希望我的第二个也是唯一的第二个标题在滚动期间“固定”到顶部,从而创建浮动标题效果。但是,在我当前的代码中,标题是固定的,但在一定的内容偏移量后会消失,但如果您向后滚动,则会重新出现。

class StickyLayout: UICollectionViewFlowLayout {

    let kind = UICollectionView.elementKindSectionHeader

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let layoutAttributes = super.layoutAttributesForElements(in: rect)

        layoutAttributes?.forEach({ (attributes) in

            if(attributes.representedElementKind == kind && attributes.indexPath.section == 1) {
                guard let collectionView = collectionView else { return }
                let contentOffset = collectionView.contentOffset.y
                var headerFrame = attributes.frame
                headerFrame.size.height = 90

                if(contentOffset > 300) {
                    headerFrame.origin.y = contentOffset
                    attributes.frame = headerFrame
                }
            }
        })
        return layoutAttributes
    }

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
 }

【问题讨论】:

标签: ios swift xcode uikit


【解决方案1】:

找到了解决办法。问题是标题在一定距离后不再位于矩形中。所以你必须在循环之前添加标题的属性。在我的 for 循环之前添加这个似乎已经解决了这个问题。

let stickyIndexPath = IndexPath(item: 0, section: 1)
if let headerAttributes = layoutAttributesForSupplementaryView(ofKind: kind, at: stickyIndexPath) {
    if !layoutAttributes!.contains(headerAttributes) {
        layoutAttributes?.append(headerAttributes)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2012-03-02
    相关资源
    最近更新 更多