テーブルビューやコレクションビューの実装

SwiftのUIKitにおける「テーブルビュー(UITableView)やコレクションビュー(UICollectionView)の実装」は、iOSアプリでリストやグリッド状のデータを表示する際に非常に重要です。以下に、それぞれの構造や実装手順、ポイントを詳しく説明します。


1. テーブルビュー(UITableView)の実装

1-1. 基本構造

UITableViewは、縦方向の1列リスト表示を行うUIコンポーネントです。

1-2. 必要な手順

(1) UITableViewの作成

Storyboard上に配置するか、コードで次のように生成します:

swift
let tableView = UITableView()

(2) データソースとデリゲートの設定

ビューコントローラがUITableViewDataSourceUITableViewDelegateプロトコルに準拠します。

swift
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // 実装略 }

(3) データソースメソッドの実装

swift
// セルの数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } // セルの内容 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = data[indexPath.row] return cell }

(4) セルの登録

swift
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

(5) レイアウトと表示

swift
view.addSubview(tableView) tableView.frame = view.bounds tableView.dataSource = self tableView.delegate = self

2. コレクションビュー(UICollectionView)の実装

2-1. 基本構造

UICollectionViewは、格子状(グリッド状)レイアウトを持ち、柔軟なカスタマイズが可能なUIコンポーネントです。

2-2. 必要な手順

(1) UICollectionViewFlowLayoutの作成

swift
let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 100, height: 100)

(2) UICollectionViewの作成

swift
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)

(3) データソースとデリゲートの設定

swift
collectionView.dataSource = self collectionView.delegate = self

(4) セルの登録と定義

swift
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")

(5) データソースメソッドの実装

swift
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) cell.backgroundColor = .blue return cell }

(6) レイアウトと表示

swift
view.addSubview(collectionView) collectionView.frame = view.bounds

3. 違いと選択の基準

特徴 UITableView UICollectionView
レイアウト 一方向(縦) 多方向(縦・横・グリッド)
カスタマイズ性 限定的 高い
複雑なレイアウト 不向き 向いている
セクションヘッダー/フッター 標準対応 カスタム必要

4. 補足:カスタムセルの実装

  • UITableViewCellUICollectionViewCellをカスタマイズするには、サブクラスを作成し、XIBまたはコードでUI部品を配置します。

  • セル登録時にクラス名を使って登録できます。

swift
tableView.register(MyCustomCell.self, forCellReuseIdentifier: "MyCell")

まとめ

  • UITableViewはシンプルなリスト表示に向いており、UICollectionViewは複雑なレイアウトを要する場合に適しています。

  • 両方ともデータソースとデリゲートの実装が必要です。

  • カスタムセルを使うことで柔軟なUI構築が可能になります。

生成日:2025/05/04