2
1

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 3 years have passed since last update.

【Swift】CollectionViewで1行あたりのセルの数を指定する

Last updated at Posted at 2021-01-30

CollectionViewで1行あたりのセルの数を指定したかったので調べました。

何も指定せずに表示した場合

こんな感じに表示されました。

どうやらセル間のスペースやサイズがデフォルトの値になっているので、セルのサイズやスペースを調整すると任意の数が表示できそうです。

1行あたりのセルの数を4個にしてみる

とりあえず、例として1行あたりのセルの数を4個表示するのをゴールに設定

これを目指します。

セルの数を指定するコード

引数numberに1行あたりに表示したい数字を入れると、希望のセル数が表示される関数を作ってみた。

private func numberOfItemsInRow(_ number: CGFloat) {
        
        let layout = UICollectionViewFlowLayout()
        let width = self.view.frame.size.width / number
        let height = width
        layout.itemSize = CGSize(width: width, height: heigh)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        collectionView.collectionViewLayout = layout
    }

解説

UICollectionViewFlowLayout()

let layout = UICollectionViewFlowLayout()

UICollectionViewのセルのitemSize等がプロパティとして用意されているオブジェクトUICollectionViewFlowLayoutをインスタンス化。
これを調整していってセルのサイズを決めていきます。

itemSize

let width = self.view.frame.size.width / number //引数number
let height = width
layout.itemSize = CGSize(width: width, height: heigh)

アイテム一個あたりのwidthself.viewの横幅を表示させたい数で割る。
heightは今回はアイテムを正方形にしたかったのでwidthと同じ値にしています。
セルの大きさを決めるitemSizewidthheightを代入

Spacing

上記のコードだけだと4個表示させたいのに希望通りの数が表示されませんでした。

スペースの大きさを考慮していなかったのが原因だった為、スペースの大きさを0にします。

layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0

minimumLineSpacingは下辺のスペース、
minimumInteritemSpacingはセル同士の間のスペース

この二つのプロパティに0を代入して、スペースを無くしました。

UICollectionViewLayout

UICollectionViewには、セルのサイズや余白等のレイアウトを管理するためのプロパティとしてUICollectionViewLayoutが用意されています。

そのUICollectionViewLayoutに作成したレイアウトを代入すると完成です。

collectionView.collectionViewLayout = layout

最後に作った関数を呼び出す

あとは、作った関数に引数を代入して呼び出して終わり。

collectionViewController.swift
override func viewDidLoad() {
    super.viewDidLoad()
        
    self.collectionView!.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
         //1行あたり4個表示させる
         numberOfItemsInRow(4)
    }

まとめ

今回はセル間のスペースを無しにしましたが、セル間のスペースを入れて希望の数を表示させたい場合は、self.view.frameの横幅に対しての一個あたりのセルの横幅だったり、minimumInteritemSpacingあたりを調整すると良さそうです。


何か間違いやより良い方法がありましたら、優しく教えていただけましたら幸いです🙇‍♂️

参考

CollectionView 列数を7にしたい

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?