概要
UICollectionViewCellを左寄せにする方法まとめTips。
方法
前提
- FlowLayoutであること。
- 縦スクロール(vertical)であること。
セルが1種類の場合
セルの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
}
}
- 各セルの
contentMode
をLeftに設定。 -
UICollectionViewFlowLayout
を継承したカスタムクラスを生成し、行ごとの最初のアイテムの左端が揃うようファンクションをオーバーライドする。 - 2で作ったクラスをCollectionViewのFlowLayoutに設定する。
※2、3をすることで、復数種類セルが混在しても左寄せになるようになる。
備考
知らないとけっこうハマる。。