14
9

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

CollectionViewで中央寄せを実現する

Posted at

概要

iOSにおけるCollectionViewは、通常左詰めでCellがレイアウトされます。
本記事では UICollectionViewDelegateFlowLayout を利用して、CollectionViewの中央にCellを配置する方法を紹介します。

やりたいこと

中央寄せレイアウト(ゴール)
center1.png
center2.png
center3.png
通常のレイアウト(参考)
left1.png
left2.png

実装

CollectionViewには、セルのsize、spacing、insetなどを設定するためのUICollectionViewDelegateFlowLayoutというプロトコルが存在します。
今回はInsetを設定することで中央寄せを実現します。
基本のUICollectionViewDelegateUICollectionViewDataSourceと合わせて、上記の実装を組み込むだけで中央寄せを実現することが出来ます。

extension UIViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let cellWidth = Int(flowLayout.itemSize.width)
        let cellSpacing = Int(flowLayout.minimumInteritemSpacing)
        let cellCount = Your Cell Count

        let totalCellWidth = cellWidth * cellCount
        let totalSpacingWidth = cellSpacing * (cellCount - 1)

        let inset = (collectionView.bounds.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2

        return UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
    }
}

参考

UICollectionViewDelegateFlowLayout
https://developer.apple.com/documentation/uikit/uicollectionviewdelegateflowlayout

14
9
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
14
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?