5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

CollectionViewの基礎〜カスタムセルで画像とタイトルを表示〜

Last updated at Posted at 2023-10-21

サンプルの概要

CollectionViewのカスタムセルを用いた実装方法を紹介します。
今回はCollectionViewに画像、文字を表示しました。
GitHubリンク: https://github.com/hinakko02/CollectionViewsSample

カスタムセルの作成方法

①StoryboardにCollectionViewをのせ、下記のように制約します!
今回はカスタムセルを作成するためCollectionViewCellは削除しておきます!
76dc28d0f42fea966fc77f660db76357.png

② CollectionViewからcontrolを押しながらViewControllerファイルに持っていき、IBOutletを作成する。
cf891838787a7a9ff25de7df746ff520 (1).png

③command + n を押し、カスタムセルのファイル作成。
CociaTouchを選択し、Nextを押す。
c72f7b3a677a56315d0ce16b02452ea2.png

③Subclass ofをUICollectionViewCellに変更する!
ClassをCollectionViewCellのままにし、Also create XIB fileのチェックし、Nextを押す。
2c9ba226e64c302f6ac604d791a551ac.png

④作成されたCollectionViewCell.xibのファイルを開く!
identifierにCollectionViewCellと入力。
a44137958b4137888de4d53844070b5c.png

⑤CollectionViewCellのWidth180、Height270にする。
c93ae45d63ef709af5472a37e2c733ef.png
⑥UIImageViewを追加し、下記のように制約する。
6f01f1078589027cb14e321d86b1bdc1.png
⑦Labelを追加し、下記のように制約する。
ff5fdf794a510e85a72740bc1d5c7969.png

⑧ UIImageViewからcontrolを押しながらCollectionViewCellファイルに持っていき、IBOutletを作成する。
Labelからcontrolを押しながらCollectionViewCellファイルに持っていき、IBOutletを作成する。
cdbb740463f8309e78d4fcc0e39d7cab.png

CollectionViewCellに表示する画像、文字が記述されたModelのCreature.swiftを作成。

Assets.xcassetsに画像を追加する。

Creature.swift
struct Creature {
    let title: String
    let image: UIImage
}

let creatures: [Creature] = [
    Creature(title: "Piyo", image: UIImage(named: "image1")!),
    Creature(title: "Chris", image: UIImage(named: "image2")!),
    Creature(title: "Ted", image: UIImage(named: "image3")!),
    Creature(title: "Isabella", image: UIImage(named: "image4")!),
    Creature(title: "Mike", image: UIImage(named: "image5")!),
    Creature(title: "Bem", image: UIImage(named: "image6")!),
    Creature(title: "Bera", image: UIImage(named: "image7")!),
    Creature(title: "Bero", image: UIImage(named: "image8")!),
    Creature(title: "Bob", image: UIImage(named: "image9")!),
    Creature(title: "Nick", image: UIImage(named: "image10")!)
]

カスタムセルとViewControllerの紐付け

下記のようにviewDidLoad()に記述する。
forCellWithReuseIdentifierに先ほどのidentifierで設定した"CollectionViewCell"を記述する。

ViewController.swift
class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
 //カスタムセルとViewControllerの紐付け
        collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionViewCell")
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.collectionViewLayout = UICollectionViewFlowLayout()
    }
}

UICollectionViewDataSource

CollectionViewCellに画像と文字を表示するためにsetUp()メソッドを作成。

CollectionViewCell.swift
class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var collectionImageView: UIImageView!
    
    @IBOutlet weak var nameLabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    func setUp(with creatures: Creature) {
        nameLabel.text = creatures.title
        collectionImageView.image = creatures.image
    }
}

ViewControllerにUICollectionViewDataSource機能を拡張する

ViewController.swift
extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return creatures.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
        cell.setUp(with: creatures[indexPath.row])
        cell.layer.borderColor = UIColor.lightGray.cgColor
        cell.layer.borderWidth = 3.0
        cell.layer.cornerRadius = 8.0
        return cell
    }
}

UICollectionViewDelegateFlowLayout

ViewControllerにUICollectionViewDelegateFlowLayout機能を拡張する

ViewController.swift
extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 180, height: 270)
    }
}

参考文献

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?