1

我有一个UICollectionViewController和要添加自定义标题。斯威夫特: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
public func layoutAttributesForSupplementaryElementOfKind(kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? 

在这里,我相信你应该能够设置帧/高度

还有headerReferenceSizeUICollectionViewFlowLayout,你可以创建collectionView时,如果它的将是静态

+0

谢谢你,Magoo!使用FlowLayout让我走向正确的方向,'headerReferenceSize'完全符合我想要达到的目标。 '让flowLayout = self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout' – ixany

+0

完美,很高兴你有它排序 – Magoo

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

+0

这个函数返回一个CGSize对象不是一个整数 –

+0

哎呀。接得好。我会更新。 – Mark