iOS-具有内容插入功能的粘性标题-标题视图不像单元格一样滚动

时间:2019-03-03 00:52:40

标签: ios uicollectionview uicollectionviewflowlayout

我们试图将UICollectionView像列表一样滚动到地图上。请勿将其与咬合到某个点(例如低,中和高)的底纸相混淆。集合视图的flowlayout属性已启用sectionHeadersPinToVisibleBounds。我已附上示例项目供您参考。当用户滚动时,标题视图是否可以移动到集合视图的顶部?

Here是示例项目

需要进行实质性更改才能进入该状态:

let layout = UICollectionViewFlowLayout()
layout.sectionHeadersPinToVisibleBounds = true
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0

let collectionView = UICollectionView(frame: .zero,
                                              collectionViewLayout: layout)


override func viewWillLayoutSubviews() {
  super.viewWillLayoutSubviews()

  collectionView.contentInset = UIEdgeInsets(top: drawerHeight, left: 0, bottom: 0, right: 0)
}

这是您看到的屏幕截图: enter image description here

红色视图是固定的标题视图。我需要一个自定义布局来在用户滚动时更新其位置吗?

2 个答案:

答案 0 :(得分:0)

我写了一个受此post启发的自定义StickyHeaderLayout。这是我的错误的解决方法:

class StickyHeaderLayout: UICollectionViewFlowLayout {

    override init() {
        super.init()
        configureLayout()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureLayout()
    }

    private func configureLayout() {
        self.sectionFootersPinToVisibleBounds = true
        self.sectionHeadersPinToVisibleBounds = true
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil }

        for attribute in attributes {
            adjustAttributesIfNeeded(attribute)
        }
        return attributes
    }

    override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        guard let attributes = super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath) else { return nil }
        adjustAttributesIfNeeded(attributes)
        return attributes
    }

    func adjustAttributesIfNeeded(_ attributes: UICollectionViewLayoutAttributes) {
        switch attributes.representedElementKind {
        case UICollectionView.elementKindSectionHeader?:
            adjustHeaderAttributesIfNeeded(attributes)
        default:
            break
        }
    }

    private func adjustHeaderAttributesIfNeeded(_ attributes: UICollectionViewLayoutAttributes) {
        guard let collectionView = collectionView else { return }
        guard attributes.indexPath.section == 0 else { return }

        if collectionView.contentOffset.y <= 0 {
            attributes.frame.origin.y = 0
        } else {
            attributes.frame.origin.y = collectionView.contentOffset.y
        }
    }
}

答案 1 :(得分:0)

一个部分是可行的,但是如果您拥有一个以上的部分,则会引起一些问题