ポイントは以下です。
- 「UICollectionViewDelegateFlowLayout」を継承すること
- UICollectionViewのオブジェクトのdelegateプロパティにselfを格納
- collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath)実装
import UIKit class CollectionViewController: UIViewController { // xibファイルのUICollectionViewと紐づけるオブジェクト @IBOutlet var goodsList: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.goodsList.delegate = self self.goodsList.dataSource = self self.goodsList.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell") } } extension CollectionViewController: UICollectionViewDataSource { // 1Sectionあたりのセルの数 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) cell.backgroundColor = .cyan return cell } } extension CollectionViewController: UICollectionViewDelegateFlowLayout { // セルのサイズを設定するメソッド func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 117, height: 132) } }
実行結果

extension CollectionViewController: UICollectionViewDelegateFlowLayout { // セルのサイズを設定するメソッド func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 180, height: 180) } }実行結果
