Swift3 – UICollectionでセルの背景色を好きな色に変える方法

こんにちわ、キングコングをIMAX3Dで見ましたが大したことなくて非常にげんなりしました。好きな映画はロッキーです。さて、UICollectionViewでCellの背景色を自由自在に変えられないかと思い、備忘録として書き残しておきます。どなたかのお役に立ててれば幸いです。

ポイント

1, indexPath.row でセルの値が取れる

2, switch文で簡単に実装できる

実装

UICollectionViewCell.swift
//データを返すメソッド
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        //コレクションビューから識別子「TestCell」のセルを取得する。
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TestCell", for: indexPath as IndexPath) as UICollectionViewCell



        //セルの背景色を設定して文字の色を変える。

        switch (true) {

        case indexPath.row == 1:

        cell.backgroundColor = UIColor.red

        case indexPath.row == 2:

        cell.backgroundColor = UIColor.blue

        case indexPath.row == 3:

        cell.backgroundColor = UIColor.orange

        case indexPath.row == 4:

            cell.backgroundColor = UIColor.yellow
        case indexPath.row == 5:

            cell.backgroundColor = UIColor.black
        case indexPath.row == 6:

            cell.backgroundColor = UIColor.white
        case indexPath.row == 7:

            cell.backgroundColor = UIColor.magenta
        case indexPath.row == 8:

            cell.backgroundColor = UIColor.brown

        case indexPath.row == 9:

            cell.backgroundColor = UIColor.darkGray

        default: break

        }  
        return cell
    }

ビルド

スクリーンショット 2017-04-11 12.23.01.png

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事