Skip to content

Instantly share code, notes, and snippets.

@satishVekariya
Created November 10, 2023 20:32
Show Gist options
  • Save satishVekariya/ab7a39a73d6fb3fdf18bcd731f4d1a8a to your computer and use it in GitHub Desktop.
Save satishVekariya/ab7a39a73d6fb3fdf18bcd731f4d1a8a to your computer and use it in GitHub Desktop.
The CarouselLayoutGenerator struct provides a convenient way to generate a UICollectionViewCompositionalLayout with a carousel-style layout.
import UIKit
/// The CarouselLayoutGenerator struct provides a convenient way to generate a UICollectionViewCompositionalLayout with a carousel-style layout.
/// This layout is suitable for creating horizontally scrolling carousels of items, commonly used in applications to showcase a series of items or images.
///
/// Example:
/// ```
/// +----------------------------+
/// | ______________________ ____|_________________ ______________________
/// | | | | | | | |
/// | | Cell1 | | | Cell2 | | Cell |
/// | | | | | | | |
/// | | | | | | | |
/// | ---------------------- ----|----------------- ----------------------
/// +----------------------------+
/// ```
///
public enum CarouselLayoutGenerator {
/// Creates and returns an NSCollectionLayoutSection configured for a carousel layout.
///
/// The section consists of a single group with horizontally arranged items.
/// Each item spans the full width of the collection view and has a height based on a specified aspect ratio.
///
/// - Returns: An NSCollectionLayoutSection configured for a carousel layout.
public static func carouselSection() -> NSCollectionLayoutSection {
let item = NSCollectionLayoutItem(
layoutSize: .init(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(1)
)
)
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: .init(
// Aspect ratio: cell width ± insets / total width ± insets
// Set cell width based on cell height
widthDimension: .fractionalHeight(1.92),
heightDimension: .fractionalHeight(1)
),
subitems: [item]
)
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .groupPaging
section.interGroupSpacing = 8
section.contentInsets = .init(top: 8, leading: 8, bottom: 8, trailing: 8)
return section
}
/// Creates and returns a UICollectionViewCompositionalLayout with a single section using the carousel layout.
///
/// - Returns: A UICollectionViewCompositionalLayout configured with the carousel layout.
public static func create() -> UICollectionViewCompositionalLayout {
UICollectionViewCompositionalLayout(section: carouselSection())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment