📦 UICollectionView の使い方

UICollectionView は、グリッドやリスト形式で複数の要素を表示する UI コンポーネントです。柔軟なレイアウトが可能で、写真一覧・カレンダー・カード表示など様々な用途に使えます。


…読み込み中…

🧱 基本の実装フロー

💡 最小構成コード(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)"

📐 レイアウトの応用

📌 よくある用途

🔗 関連リンク