【Swift】CollectionViewを使ってみた

CollectionViewを使ってサンプルアプリを作ってみました。

レストランのカテゴリー一覧を表示する感じです。

CollectionViewはTableViewなどと使い方が似ています。

ストーリーボード上でCollectionViewのセルのサイズやスクロール方向などを設定します。

左の画像のようにCollection View Flow Layoutが追加されますのでこれを使って、セルのサイズを設定しました。

EstimateSizeNoneにすることでセルのサイズを固定しました。

私はスクロール方向を縦方向(Vertical)にしていますが、横方向にすることもできます。

1つ1つのセルは`UICollectionViewCell`を継承して作っていきます。

import UIKit

class CollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageview: UIImageView!
    @IBOutlet weak var janre: UILabel!
}

画像とラベルをストーリーボードからアウトレット接続しています。

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と同じです。

それでは。

ABOUTこの記事をかいた人

個人アプリ開発者。Python、Swift、Unityのことを発信します。月間2.5万PVブログ運営。 Twitter:@yamagablog