LoginSignup
0
1

More than 3 years have passed since last update.

2列のCollectionViewの余白を埋めて横幅いっぱいにする(伝われ

Last updated at Posted at 2021-01-26

Storyboardだけでは固定値しか設定出来ない関係で不可。古いやり方でAutoResizingというのもあったそうだが、今は基本は3つくらいのやり方に集約されているようだ

Storyboardを使っていて、ViewControllerの中にCollectionViewとCellを入れている場合(Xibを使っていない)場合はデリゲートUICollectionViewDelegateFlowLayoutを使うのがよさそう。
スクリーンショット 2021-01-26 16.56.43.png

extension ViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let spaceForCells: CGFloat = 3
        let cellWidth: CGFloat = (self.view.bounds.width / 2) - (spaceForCells / 2)
        let cellHeight: CGFloat = (cellWidth * 235 / 156)
        return CGSize(width: cellWidth, height: cellHeight)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 3
    }
}

Cellの横幅

まずCellの横幅は画面横幅の半分から余白分を引いた長さになる。ただし、デフォルトでは左右それぞれにCellがひっついているレイアウトになり、1つ目のCellは右側に余白ができ、2つ目のCellは左側に余白ができる。なので引くべき値はStoryboard上でのMin Spacing For Cellsにあたる値の半分となる。
スクリーンショット 2021-01-26 17.08.08.png
(↑セクションの左のセルは右余白のみが、右のセルは左余白のみができる)

ちなみに余白を引かずに画面横幅のピッタリ半分にしてStoryboardでMin Spacing For Cellsを0以上とかに設定しちゃってると1列になっちゃう。

Cellの縦幅

今回はすべてのCollectionViewの縦横比を固定したい。インスタのストーリーなどは「1080 x 1920」の「9:16」だが、最低3列は見えてほしかったので「156:235」にした。ここは任意で変えてほしい。

参考リンク

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