【问题标题】:Swift: Header of UICollectionViewController overlaps cellsSwift:UICollectionViewController 的标题与单元格重叠
【发布时间】:2016-11-18 13:26:48
【问题描述】:

我有一个UICollectionViewController 并想添加一个自定义标题。

我在 CollectionViewController 的 Interface Builder 中检查了Section Header,并在我的子类中实现了viewForSupplementaryElementOfKind 函数。

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    switch kind {

    case UICollectionElementKindSectionHeader:

        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "myHeaderIdentifier", for: indexPath)

        // !! NOT WORKING PROPERLY
        // sectionHeader overlaps other cells

        headerView.backgroundColor = UIColor(hue: 0.9, saturation: 1.0, brightness: 0.9, alpha: 1.0)
        headerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 250.0)

        return headerView

    default:
        assert(false, "Unexpected element kind")
    }

}

更改生效,但标题(下面屏幕截图中的粉红色区域)现在与 collectionView 中的常规单元格重叠。

我做错了什么? 感谢任何帮助!

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell uicollectionreusableview


    【解决方案1】:
    public func layoutAttributesForSupplementaryElementOfKind(kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
    

    这里我相信你应该可以设置框架/高度

    UICollectionViewFlowLayout 中还有 headerReferenceSize,如果它是静态的,您可以在创建 collectionView 时设置它

    【讨论】:

    • 谢谢你,Magoo!使用 FlowLayout 让我走向了正确的方向,headerReferenceSize 正是我想要实现的目标。 let flowLayout = self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout
    • 完美,很高兴你整理好了
    【解决方案2】:

    UICollectionViewDelegateFlowLayout 协议中使用此方法:

    optional func collectionView(_ collectionView: UICollectionView, 
                      layout collectionViewLayout: UICollectionViewLayout, 
          referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: UIScreen.main.bounds.width, height: 250.0)
    }
    

    确保将您的类设置为流布局的委托。您可以找到更多信息here

    【讨论】:

    • 这个函数返回一个 CGSize 对象而不是一个整数
    猜你喜欢
    • 2019-09-16
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    相关资源
    最近更新 更多