UICollectionViewとは
UICollectionViewはアマゾンの商品検索結果のページのように、縦横に整列させてセルを表示させるのに使われます。目次
UICollectionViewを表示するには以下の手順を踏めばできます。- UICollectionViewを表示したい画面のxibファイルにUICollectionViewを設置する
- 設置したUICollectionViewのAutoLayoutを設定する
- 設置したUICollectionViewをxibファイルのソースコードで定義したUICollectionView型のオブジェクトと結びつける
- デリゲートメソッドを使用してセルを表示の設定を行う
- 自分で独自のセルを作成し、表示する
UICollectionViewを表示したい画面のxibファイルにUICollectionViewを設置する
ソースコードで定義したUICollectionView型のオブジェクトと結びつける
ソースコード上の定義import UIKit class CollectionViewController: UIViewController { // xibファイルのUICollectionViewと紐づけるオブジェクト @IBOutlet var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() } }xibファイル上の操作
デリゲートメソッドを使用してセルを表示の設定を行う
import UIKit class CollectionViewController: UIViewController { // xibファイルのUICollectionViewと紐づけるオブジェクト @IBOutlet var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self self.collectionView.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 } }
実行結果

自分で独自のセルを作成し、表示する
新たにCollectionViewCellクラスを作成します。時には、画像をいれたい、アマゾンのように画像の下に商品名などを記載したい場合もあるでしょう。
その場合は、UICollectionViewCellを使用します。
xibファイル、ファイル構成は今のような状態です。

import UIKit class CollectionViewCell: UICollectionViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
import UIKit class CollectionViewController: UIViewController { // xibファイルのUICollectionViewと紐づけるオブジェクト @IBOutlet var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self self.collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), 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 } }
実行結果
