キノコが何か作るブログ

ゲーム・ドット絵・アプリなどを作ります

MENU

とりあえずCollectionViewでカスタムセルを使う方法【備忘録】

使用するswiftのバージョン

  • swift : swift5
  • xcode : Version 11.4.1

こんな感じのが出来上がります

f:id:mizukinoko:20200507085712p:plain
ビルドした時の画面

CocoaTourchでカスタムセルファイルを作る

File→New→FileでCocoaTourchを選択。Nextを押す。
f:id:mizukinoko:20200507081236p:plain

ファイル名をCustomCellにし、「Also create XIB file」にチェックを入れる。
また、Subclass of:を「UICollectionViewCell」にすること。
f:id:mizukinoko:20200507081156p:plain

CustomCell.xibの設定

セルにラベルを追加する。
f:id:mizukinoko:20200507081442p:plain

次にクラス指定をCustomCellにする。
f:id:mizukinoko:20200507082244p:plain

CustomCell.swiftの設定

先ほど追加したラベルを紐づける。
f:id:mizukinoko:20200507081656p:plain

そしたら自作セルを適当にカスタマイズする。
自分はこんな感じにした。

import UIKit

class CustomCell: UICollectionViewCell {
    
    @IBOutlet weak var dayLabel: UILabel!
    
    override func prepareForReuse() {
        contentView.backgroundColor = .lightGray
    }
    
    func setText(_ text: String?) {
        dayLabel.text = text
    }
    
    func setBackgroundColor(_ color: UIColor) {
        contentView.backgroundColor = color
    }
}

Storyboardの設定

普通にCollectionViewを追加して、画面いっぱいに表示させる。
f:id:mizukinoko:20200507082533p:plain

CollectionViewのDataSourceとDelegateをViewControllerに紐付けする。
先ほど貼り付けたCollectionViewを選択し、Controlを押しながら上の黄色いやつまで引っ張る。
f:id:mizukinoko:20200507082843p:plain
そしたら黒い画面が出てきてDelegateとDataSourceっていうのがでてくるからクリックしておく。
一度に一個しか紐付けできないから、2回やって両方とも紐付けする。

ViewControllerの設定

ViewController.swiftにこんな感じでコードを書く。

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 30
    }
}

自作セルを登録して使えるようにする。
viewDidLoad関数を以下のように書き換える。

override func viewDidLoad() {
        super.viewDidLoad()
        
        let nib = UINib(nibName: "CustomCell", bundle: nil)
        collectionView!.register(nib, forCellWithReuseIdentifier: "Cell")
    }

するとcollectionViewがねぇぞと怒られるので、CollectionViewをViewController.swiftに紐付けする。
f:id:mizukinoko:20200507084127p:plain

エラーが一個出ているので、次のコードを書き足す。今回はviewdidLoad関数の真下に追加した。

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        //CustumCellを宣言する
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
        //色々いじる
        cell.setText("Hello")
        cell.setBackgroundColor(.lightGray)
        
        return cell
    }
}

最後にViewController.swiftの全文を載せておきます

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let nib = UINib(nibName: "CustomCell", bundle: nil)
        collectionView!.register(nib, forCellWithReuseIdentifier: "Cell")
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        //CustumCellを宣言する
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
        //色々いじる
        cell.setText("Hello")
        cell.setBackgroundColor(.lightGray)
        
        return cell
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 30
    }
}
プライバシーポリシー