[英]Swift - Change height of CollectionView Header
我想更改我的CollectionViewController
標題的高度。
我已經知道我可以使用這樣的代碼:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: 250)
}
我想這樣做,但直接在 UICollectionReusableView(標題視圖)中。
有沒有允許這樣做的功能?
您需要添加UICollectionViewDelegateFlowLayout
。
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 40)
}
}
要動態更改標題大小,請使用headerReferenceSize UICollectionViewFlowLayout 屬性。
let collectionViewLayout = UICollectionViewFlowLayout()
collectionViewLayout.headerReferenceSize = CGSize(width: view.frame.size.width, height: 80)
確保不包含referenceSizeForHeaderInSection委托方法以使其工作。
collectionview 中的標題與 tableview 不同,因為您需要創建不同類型的單元格,此單元格名為UICollectionReusableView
,使用此名稱創建一個類,然后在您的 collectionview 中選中此選項:在此處輸入圖像描述
然后你可以用這個函數在代碼上調用它:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.