gpt4 book ai didi

ios - 如何创建跨越多个部分的粘性标题

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:01:03 24 4
gpt4 key购买 nike

我有一个 Collection View ,其中每个单元格都是一个部分。我需要实现一个跨越 3 个部分的“粘性 header ”,直到另一个“粘性 header ”取代它。我怎样才能做到这一点?由于其他原因,我无法将我的单元格更改为共享同一部分。

最佳答案

我将仅在第一部分演示如何执行此操作。它很不成熟,因为使用了一些常量。然而,如果你遵循这个模式,你可以更容易地实现你的目标。

为了达到高精度,请随意更改代码。

基本上,只需继承 UICollectionViewFlowLayout。

class MyCollectionViewFlowLayout: UICollectionViewFlowLayout{

lazy var offset : CGFloat? = { return self.collectionView?.contentOffset.y}()

// only first section here, you need to add other sections programmatically later.
override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext{
let result = super.invalidationContext(forBoundsChange: newBounds)
result.invalidateSupplementaryElements(ofKind: UICollectionView.elementKindSectionHeader, at: [IndexPath.init(row: 0, section: 0)])
return result
}


override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?{
let result = super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath)
guard indexPath.section % 3 == 0 else {
return result
}
let section = CGFloat (indexPath.section / 3)

let totalHeight : CGFloat = 414.0 + 1390.0 * (section) //414 = first section height
// 1390 = height of three sections
let totalNextHight : CGFloat = 1390.0 * (section + 1)

if let result = result {
if result.frame.origin.y > CGFloat(totalHeight) {
result.frame = CGRect.init(x: result.frame.origin.x , y: (result.frame.origin.y < totalNextHight) ? (self.collectionView?.contentOffset.y)! - offset! + totalHeight : totalNextHight, width: result.frame.width, height: result.frame.height)

}
}
return result
}

正如我所说,这仅适用于第一个粘性 header 。我像这样在委托(delegate)中定义了 header 大小:

extension MyCollectionViewController: UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
if section % 3 == 0 {return CGSize.init(width:200 , height: 44)}
return CGSize.init(width:0 , height: 0)
}

这些代码背后有很多工作要做。希望您能尽快找到自己的问题答案。

关于ios - 如何创建跨越多个部分的粘性标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52897057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com