LoginSignup
0
3

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-04-11

こんにちわ、キングコングを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 indexPath.row {

        case 1:

            cell.backgroundColor = .red

        case 2:

            cell.backgroundColor = .blue

        case 3:

            cell.backgroundColor = .orange

        case 4:

            cell.backgroundColor = .yellow

        case 5:

            cell.backgroundColor = .black

        case 6:

            cell.backgroundColor = .white

        case 7:

            cell.backgroundColor = .magenta

        case 8:

            cell.backgroundColor = .brown

        case 9:

            cell.backgroundColor = .darkGray

        default: break

        }

        return cell
    }

ビルド

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

0
3
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3