Swift-更改CollectionView标头的高度

时间:2018-08-07 17:03:01

标签: ios swift swift3 uicollectionview resize

我想更改CollectionViewController的标题的高度。

我已经知道我可以使用这样的代码:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: collectionView.frame.size.width, height: 250)
}

我想这样做,但是直接在UICollectionReusableView(标题视图)中。

有没有允许的功能?

3 个答案:

答案 0 :(得分:1)

要动态更改标题大小,请使用 headerReferenceSize UICollectionViewFlowLayout属性。

let collectionViewLayout = UICollectionViewFlowLayout()
collectionViewLayout.headerReferenceSize = CGSize(width: view.frame.size.width, height: 80)

确保包括 referenceSizeForHeaderInSection 委托方法以使其起作用。

答案 1 :(得分:0)

您需要添加UICollectionViewDelegateFlowLayout

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout {

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

    return CGSize(width: collectionView.frame.width, height: 40)
  }
}

答案 2 :(得分:0)

collectionview中的标题与tableview不同,因为您需要创建不同类型的单元格,该单元格名为UICollectionReusableView,使用此名称创建一个类,然后在您的collectionview中检查以下选项: enter image description here

然后您可以使用以下函数在代码上调用它:

override func collectionView(_ collectionView: UICollectionView,
                             viewForSupplementaryElementOfKind kind: String,
                             at indexPath: IndexPath) -> UICollectionReusableView {
  //1
  switch kind {
  //2
  case UICollectionElementKindSectionHeader:
    //3
    let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
                       withReuseIdentifier: "UICollectionReusableViewID",
                       for: indexPath) as! UICollectionReusableViewClass
//Customize

    return headerView
  default:
    //4
    assert(false, "Unexpected element kind")
  }
}

所有积分RayWenderLich教程:https://www.raywenderlich.com/1404-uicollectionview-tutorial-reusable-views-selection-and-reordering

相关问题