LoginSignup
73
75

More than 3 years have passed since last update.

CollectionViewの基礎

Last updated at Posted at 2017-11-02

はじめに

今回は、UINavigationControllerとUICollectionViewControllerとUIViewControllerを使いました。主に、CollectoinViewの使い方を記しました。

完成品

cellをタップすると、簡単な画面遷移とデータの移行をしています。

スクリーンショット 2018-05-12 11.18.40.png
スクリーンショット 2018-05-12 11.18.50.png

作ってみよう

まずは、storyboardの設定をします。
全体像としては次のようになります。
スクリーンショット 2018-05-12 11.20.33.png

CollectionViewControllerのcellにはLabelを2つ置いています。
スクリーンショット 2018-05-12 11.20.45.png

cellに配置されている色のLabelを丸くしたいので、Labelを選択して、次のように設定してください。
スクリーンショット 2018-05-12 11.36.10.png

Clip To Boundsにもチェックを入れておいてください。
スクリーンショット 2018-05-12 11.37.04.png

そして、一番右のViewControllerの全面にはLabelを設置しています。
スクリーンショット 2018-05-12 11.21.10.png

CollectionViewControllerからViewControllerの画面遷移にはSegueを使いましたが、このSegueのIdentifierは"Segue"にしています。
スクリーンショット 2018-05-12 11.25.19.png

また、CellのIdentifierを"CollectionViewCell"にしています。
スクリーンショット 2018-05-12 11.41.42.png

次にNewFileから、UICollectionViewControllerを継承しているCollectionViewController.swiftというファイルとUICollectionViewCellを継承しているCollectionViewCell.swiftというファイルを作ってください。
スクリーンショット 2018-05-12 11.27.34.png

そして、storyboardのCollectionViewControllerとCollectionViewCellにクラスの関連付けをします。
スクリーンショット 2018-05-12 11.28.54.png

スクリーンショット 2018-05-12 11.29.02.png

CollectionViewCell.swiftのCollectionViewCellというクラスにstoryboardのcellの2つのラベルを関連付けましょう。

CollectionViewCell.swift
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var name: UILabel!

そして、CollectionViewCellのクラス内でrequired init?(coder aDecoder: NSCoder)という関数を作ります。ここでは、cellの枠の色つけと丸くするコードを書きます。
CollectionViewCell.swiftの全体のコードは次のようになります。

CollectionViewCell.swift
class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var name: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // cellの枠の太さ
        self.layer.borderWidth = 1.0
        // cellの枠の色
        self.layer.borderColor = UIColor.black.cgColor
        // cellを丸くする
        self.layer.cornerRadius = 8.0
    }
}

次はCollectionViewController.swiftにコードを書いていきます。
説明などはコメントアウトに書きました。

CollectionViewController.swift
class CollectionViewController: UICollectionViewController {

    // cellの色の配列
    let colors: [UIColor] = [UIColor.black, UIColor.blue, UIColor.brown, UIColor.cyan, UIColor.darkGray, UIColor.darkText, UIColor.gray, UIColor.green, UIColor.lightGray, UIColor.orange, UIColor.red]
    // cellの色の名前の配列
    let colorNames: [String] = ["black", "blue", "brown", "cyan", "darkGray", "darkText", "gray", "green", "lightGray", "orange", "red"]

    // 画面遷移先に渡す色
    var giveColor: UIColor = UIColor.black
    // 画面遷移先に渡す色の名前
    var giveColorName: String = "black"

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // cellの数を返す関数
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return colors.count
    }

    // cellに情報を入れていく関数
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // Identifierが"CollectionViewCell"でCollectionViewCellというクラスのcellを取得
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell

        // cellのlabelに色付け
        cell.label.backgroundColor = colors[indexPath.item]
        // cellのnameに色の名前を入れる
        cell.name.text = colorNames[indexPath.item]

        return cell
    }

    // cell選択時に呼ばれる関数
    // 画面遷移先に渡すデータをここで格納する
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        giveColor = colors[indexPath.item]
        giveColorName = colorNames[indexPath.item]
        // Identifierが"Segue"のSegueを使って画面遷移する関数
        performSegue(withIdentifier: "Segue", sender: nil)
    }

    // 画面遷移先のViewControllerを取得し、データを渡す
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "Segue" {
            let vc = segue.destination as! ViewController
            vc.receiveColor = giveColor
            vc.receiveColorName = giveColorName
        }
    }
}

ViewController.swiftのコードは次のようになります。

ViewController.swift
class ViewController: UIViewController {

    @IBOutlet weak var backgroundLabel: UILabel!

    // CollectionViewControllerから渡される色のデータ
    var receiveColor: UIColor = UIColor.black
    var receiveColorName: String = "black"

    override func viewDidLoad() {
        super.viewDidLoad()
        // 背景の色を渡された色にする
        backgroundLabel.backgroundColor = receiveColor
        // NavigationItemと呼ばれる一番上のバーに色の名前を入れる
        self.navigationItem.title = receiveColorName
    }
}

これで完成になります。

最後に

このコードは、githubにあげておきます。

73
75
0

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
73
75