【问题标题】:Different layout for different sections in collection view集合视图中不同部分的不同布局
【发布时间】:2019-12-31 18:37:19
【问题描述】:

我有一个包含 3 个部分的集合视图,前两个部分与 UICollectionViewFlowLayout 一起工作正常,但第三个部分需要自定义实现。

我知道集合视图只能有一种布局,因此我一直在尝试仅在正确的部分中执行覆盖的准备功能中的工作。这是它趋于崩溃的地方,我无法找到一种直接的方法来确定单元格所在的部分,我正在为其计算布局属性。

不确定是否有比在准备函数中有条件地执行计算更好的方法。

一个方向正确的点会很棒!

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewlayout uicollectionviewflowlayout


    【解决方案1】:

    我认为这是一个很好的方法:

    1- 使用自己的 .xib 文件创建您的自定义部分

    class CustomSection: UICollectionReusableView {
    
        override func awakeFromNib() {
            super.awakeFromNib()
        }
    }
    

    2- 实现 UICollectionViewDelegateFlowLayout 委托方法

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    
            // In case its a section header (UICollectionElementKindSectionFooter for footer)
            if kind == UICollectionElementKindSectionHeader {
    
                // This will be the section number
    
                let section = indexPath.section
    
                if section == 3 {
    
                    let customSection = collectionView.dequeueReusableSupplementaryView(ofKind: kind,withReuseIdentifier: "CustomSection", for: indexPath) as! CustomSection
                    return customSection
    
                }
                else {
    
                   //TODO: Return your default section
    
                }
    
            }
    }
    

    3- 不要忘记使用您的 UICollectionView 注册该部分

    let customSectionNib = UINib.init(nibName: "CustomSection", bundle: nil)
            collectionView.register(customSectionNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CustomSection")
    

    【讨论】:

      猜你喜欢
      • 2016-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 2021-11-20
      • 2013-04-23
      • 1970-01-01
      相关资源
      最近更新 更多