LoginSignup
4
3

More than 5 years have passed since last update.

[Tips] UICollectionViewCell左寄せ

Last updated at Posted at 2018-12-24

XQWtB.png

概要

UICollectionViewCellを左寄せにする方法まとめTips。

方法

前提

  • FlowLayoutであること。
  • 縦スクロール(vertical)であること。

セルが1種類の場合

スクリーンショット 2018-12-24 16.39.01.png

セルのcontentModeをLeftに設定。

セルが複数種類の場合

final class LeftAlignmentCollectionViewFlowLayout: UICollectionViewFlowLayout {
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return super.layoutAttributesForElements(in: rect)?
            .reduce(into: [UICollectionViewLayoutAttributes]()) { result, attribute in
                let isFirstCellInColumn: Bool = {
                    if attribute.representedElementCategory != .cell {
                        return false
                    } else if let previousAttribute = result.last,
                        previousAttribute.frame.origin.y + previousAttribute.frame.height >= attribute.frame.origin.y {
                        return false
                    } else {
                        return true
                    }
                }()
                if isFirstCellInColumn {
                    attribute.frame.origin.x = self.sectionInset.left
                }
                result += [attribute]
        }
    }

    // ==================================================
    // レイアウト開始時の動きを制御する必要がある場合、上記と合わせて追加する
    // ==================================================
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        guard let attribute = super.layoutAttributesForItem(at: indexPath) else {
            return nil
        }
        let isFirstCellInColumn: Bool = {
            if indexPath.item > 1,
                let previousAttribute = super.layoutAttributesForItem(at: IndexPath(item: indexPath.item - 1, section: indexPath.section)),
                previousAttribute.frame.origin.y + previousAttribute.frame.height >= attribute.frame.origin.y {
                return false
            } else {
                return true
            }
        }()
        if isFirstCellInColumn {
            attribute.frame.origin.x = self.sectionInset.left
        }
        return attribute
    }
}

スクリーンショット 2018-12-24 16.39.08.png

  1. 各セルのcontentModeをLeftに設定。
  2. UICollectionViewFlowLayoutを継承したカスタムクラスを生成し、行ごとの最初のアイテムの左端が揃うようファンクションをオーバーライドする。
  3. 2で作ったクラスをCollectionViewのFlowLayoutに設定する。

※2、3をすることで、復数種類セルが混在しても左寄せになるようになる。

備考

知らないとけっこうハマる。。

4
3
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
4
3