CollectionViewを使ってサンプルアプリを作ってみました。
レストランのカテゴリー一覧を表示する感じです。
CollectionViewはTableViewなどと使い方が似ています。
ストーリーボード上でCollectionViewのセルのサイズやスクロール方向などを設定します。

左の画像のようにCollection View Flow Layout
が追加されますのでこれを使って、セルのサイズを設定しました。
EstimateSize
をNone
にすることでセルのサイズを固定しました。
私はスクロール方向を縦方向(Vertical)にしていますが、横方向にすることもできます。
1つ1つのセルはUICollectionViewCell
を継承して作っていきます。
1 2 3 4 5 6 |
import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageview: UIImageView! @IBOutlet weak var janre: UILabel! } |
画像とラベルをストーリーボードからアウトレット接続しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class CollectionViewController: UICollectionViewController { var categoryList = Utility().categoryList override func viewDidLoad() { super.viewDidLoad() } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return categoryList.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell let index = indexPath.row cell.janre.text = categoryList[index].name cell.imageview.image = UIImage(named: String(index)) return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print(categoryList[indexPath.row]) } } |
ViewControllerはこんな感じ。
ほぼTableViewControllerと同じです。
それでは。