Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hmhmsh/3f918315b0bf3d569b12c735aee8bfc3 to your computer and use it in GitHub Desktop.
Save hmhmsh/3f918315b0bf3d569b12c735aee8bfc3 to your computer and use it in GitHub Desktop.
UICollectionViewCompositionalLayout + Carousel
struct LayoutGenerator {
static func generate(handler: @escaping (Int) -> NSCollectionLayoutSection?) -> UICollectionViewCompositionalLayout {
return .init { section, environment in
handler(section)
}
}
}
struct SectionLayoutGenerator {
static func carousel(width: CGFloat, height: CGFloat, spacing: CGFloat = 8) -> NSCollectionLayoutSection {
let item = NSCollectionLayoutItem(
layoutSize: .init(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(1)
)
)
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: .init(
widthDimension: .absolute(width),
heightDimension: .absolute(height)
),
subitems: [item]
)
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .continuous
section.interGroupSpacing = spacing
section.contentInsets = .init(top: 0, leading: 20, bottom: 0, trailing: 20)
return section
}
}
private func createLayout() -> UICollectionViewLayout {
LayoutGenerator.generate { section in
// section: Intなので場合分けができる
return SectionLayoutGenerator.carousel(width: 100, height: 100)
}
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.collectionViewLayout = createLayout()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment