Swift:UICollectionViewController的标头与单元格重叠

时间:2016-11-18 13:26:48

标签: ios swift uicollectionview uicollectionviewcell uicollectionreusableview

我有一个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中的常规单元格重叠。

enter image description here

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

2 个答案:

答案 0 :(得分:2)

public func layoutAttributesForSupplementaryElementOfKind(kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?

我相信你应该可以设置帧/高度

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

答案 1 :(得分:1)

使用UICollectionViewDelegateFlowLayout协议中的此方法:

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

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

相关问题