Last active
August 12, 2021 01:10
-
-
Save hmhmsh/3f918315b0bf3d569b12c735aee8bfc3 to your computer and use it in GitHub Desktop.
UICollectionViewCompositionalLayout + Carousel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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