【Swift】コードのみでCollectionViewの作成

Swift

swiftにおいてよく使うCollectionViewをコードのみで実装しました。
お役に立てれば幸いです。

CollectionView

CollectionViewとは

・多くのアイテムをパネルのように一覧として表示させるもの

・縦方向、横方向ともに並べることが可能

実装

実装したもの

コードのみで実装できるように設定

こちらは前回説明しているものがあるので詳しくは解説しません。
よければご参考ください。

コードでコレクションビューを作成

ViewControllerを作る前にスクリーンサイズを宣言しておきます。

let screenSize: CGSize = CGSize(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)

その後コレクションビューの作成、登録を実装

    let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.width), collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        //コレクションビューの登録
        collectionView.register(CollectionViewCell.self,forCellWithReuseIdentifier: "cellId")
        return collectionView
    }()

Cell.swiftファイルを作成してcellの詳細を設定

今回はcell同士の間のボーダーの色と幅を設定してだけのシンプルなもの

class CollectionViewCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        layer.borderColor = UIColor.darkGray.cgColor
        layer.borderWidth = 3.0
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

DataSource,Delegateを設定

忘れがちな設定をいつも通り設定

collectionView.dataSource = self
collectionView.delegate = self

ViewControllerのクラス部分に下記記載も忘れないようにする

class ViewController: UIViewController, 
UICollectionViewDataSource , UICollectionViewDelegate {

関数でCellの設定

下記2つは最低限必ず実装が必要な関数

  //cellの数を設定   
 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }

//cellの中身を設定
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “cellId”, for: indexPath)
        
        return cell
    }

FlowLayoutでCellのサイズを設定

細かくレイアウトを設定できる関数がいくつも用意させているが今回は下記の実装のみ
(色々と柔軟に実装ができそう)

// コレクションビューのレイアウト設定
extension ViewController: UICollectionViewDelegateFlowLayout {
    //cellの大きさ
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return CGSize(width: 100, height: 100)
    }
    
    // 水平方向におけるセル間のマージン
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

viewに作成したコレクションビューの追加&デフォルトの設定解除

こちらも忘れがちなので忘れないように実装

    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(collectionView)
    }

参考サイト

○公式

UICollectionView | Apple Developer Documentation
An object that manages an ordered collection of data items and presents them using customizable layouts.

○コードでこくクションビュー

コードのみでcollectionViewの作成 - Qiita
storyboardを使わずにコードのみで記述されている情報少ないなーと思い、これからコードのみで書いていきたいという人(少数だとは思いますが)がいた時のための保存です。##コードのみでアプリを…

○レイアウトについて

最後に

もっと色々と工夫すればできることが無限にありそうなコレクションビュー。
随時更新できればと思います。

コメント

タイトルとURLをコピーしました