我想在标题和实际项目之间添加一些间距,目前看起来像这样:
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
// Create header
switch kind{
case UICollectionElementKindSectionHeader:
let headerView = iconCollectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "customIconHeaderView", forIndexPath: indexPath) as! CustonIconHeaderView
headerView.setUp() //add whatever into the view
return headerView
default:
assert(false, "Unexpected element kind")
}
}
答案 0 :(得分:24)
您基本上是在为集合视图部分添加上边距,因为您可以为该部分设置 top inset 。要在代码中执行此操作,请实现insetForSectionAtIndex
:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 10.0, left: 1.0, bottom: 1.0, right: 1.0)
}
如果您不想实施insetForSectionAtIndex
,您也可以使用适当的方法执行此类操作,例如viewDidLoad
:
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets(top: 10.0, left: 1.0, bottom: 1.0, right: 1.0)
在Interface Builder中,选择集合视图并更改 Section Insets - >的值。顶部,如下图所示:
注意:仅在使用Flow Layout时才有效。
答案 1 :(得分:1)
您可以采取的一种方法是使用
增加标题容器的高度 collectionView(_:layout:referenceSizeForHeaderInSection:)
示例:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: 0, height: yourHeaderContentHeight + yourHeaderMarginToCell)
}
修改强>
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "YourID", forIndexPath: indexPath)
let yourCustomView = UIView(frame: CGRect(x: 0, y: 0, width: yourHeaderWidth, height: yourHeaderHeight))
headerView.addSubview(yourCustomView)
return headerView
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: yourHeaderWidth, height: yourHeaderHeight + yourHeaderMargin)
}