OGeek|极客世界-中国程序员成长平台

标题: ios - 如何创建一个跨越多个部分的粘性标题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:42
标题: ios - 如何创建一个跨越多个部分的粘性标题

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



Best Answer-推荐答案


我将仅在第一部分演示如何执行此操作。它还很不成熟,因为使用了一些常量。但是,如果您遵循该模式,则可以更轻松地实现目标。

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

基本上,只是子类化 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
}

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

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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4