🧱 基本の実装フロー
- レイアウト(UICollectionViewFlowLayout)を定義
- UICollectionViewを生成してViewに追加
- セルを登録(register)
- データソース・デリゲートを設定
💡 最小構成コード(Swift)
class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 100, height: 100)
layout.scrollDirection = .vertical
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = .white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
view.addSubview(collectionView)
}
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 = .systemBlue
return cell
}
}
🎨 カスタムセルの登録
独自のセルを使いたい場合は、UICollectionViewCell を継承してカスタムクラスを作成します。
class MyCell: UICollectionViewCell {
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
label.frame = contentView.bounds
label.textAlignment = .center
contentView.addSubview(label)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
登録と使用例:
collectionView.register(MyCell.self, forCellWithReuseIdentifier: "myCell")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCell
cell.label.text = "Item \(indexPath.row)"
📐 レイアウトの応用
scrollDirection: `.horizontal` や `.vertical`minimumLineSpacing: 行間minimumInteritemSpacing: アイテム間sectionInset: 外枠の余白
📌 よくある用途
- 画像ギャラリー
- カード風リスト表示
- 日付や時間の選択
- 横スクロールのレイアウト