概要
CollectionViewでSectionHeaderを表示させたいと考えているのですがうまくいかず困っています。
セルのサイズと左右のマージンなどを独自の値にしたいと考えているのでCollectionFlowLayoutをCollectionViewに設定しているのですがこれがも問題なのでしょうか?
どうやってどちらも設定すれば良いのでしょうか?
swift
class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! { didSet { collectionView.delegate = self collectionView.dataSource = self collectionView.register(UINib(nibName: "SampleCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell") collectionView.register(UINib(nibName: "SampleSectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "SampleSectionHeaderView") } } override func viewDidLoad() { super.viewDidLoad() let layout = CollectionFlowLayout() let sideMargin: CGFloat = 30 let sideAllMargin = sideMargin * 2 + 24 let width = (self.view.frame.width - sideAllMargin) / 2 layout.itemSize = CGSize(width: width, height: 300) //セル同士の隙間 layout.minimumInteritemSpacing = 24 //セル同士の高さの隙間 layout.minimumLineSpacing = 24 layout.sectionInset = UIEdgeInsets(top: 16, left: sideMargin, bottom: 0, right: sideMargin) collectionView.collectionViewLayout = layout } } extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 20 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! SampleCollectionViewCell cell.hogeView.backgroundColor = .white return cell } // Sectionの設定 // 呼ばれる func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } // 呼ばれない func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: self.view.frame.width, height: 100) } // 呼ばれない func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "SampleSectionHeaderView", for: indexPath) return view } }
まだ回答がついていません
会員登録して回答してみよう