Skip to content

Create dynamic and modern collections effortlessly without relying on enums with AnyLayout.

License

Notifications You must be signed in to change notification settings

OfTheWolf/AnyLayout

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AnyLayout

Create dynamic and modern collections effortlessly without relying on enums with AnyLayout.

AnyLayout simplifies building UI collections using UICollectionViewCompositionalLayout with type erasure for flexibility.

Demo

Installation

Integrate AnyLayout into your project using Swift Package Manager:

Xcode > File > Add Package Dependencies.. : https://github.com/OfTheWolf/AnyLayout.git

Getting Started

  1. Inherit from CollectionViewController.
class ViewController: CollectionViewController {}
  1. Define sections conforming to SectionProviding. Implement the layout method to configure the section layout.
struct ListSection: SectionProviding {
    let id = UUID()
    
    // Define section layout here
    func layout(_ sectionIndex: Int, _ layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection {
        // Configure section layout
    }
}
  1. Define items conforming to ItemProviding.
struct TextItem: ItemProviding {
    let text: String
}
  1. Implement cell registration and dequeueing.
extension TextCell: Registering {
    typealias Cell = TextCell
    typealias Item = TextItem

    /// Boilerplate code
    static var registration: UICollectionView.CellRegistration<Cell, AnyItem> = UICollectionView.CellRegistration<Cell, AnyItem> { cell, indexPath, itemIdentifier in
        let data: Item = itemIdentifier.resolve()
        cell.configure(with: data)
    }
}

extension TextCell: Dequeueing {
    /// Boilerplate code
    static func dequeueCell(_ collectionView: UICollectionView, indexPath: IndexPath, item: AnyItem) -> UICollectionViewCell {
        return collectionView.dequeueConfiguredReusableCell(using: Self.registration, for: indexPath, item: item)
    }
}
  1. Register your cell types with their corresponding item types.
//    MARK: - Override
    override func registerCells(for collectionView: UICollectionView) {
        collectionView.register(cell: ImageCell.self, item: ImageItem.self)
        collectionView.register(cell: TextCell.self, item: TextItem.self)
    }
  1. Prepare the snapshot with your data.
    private func loadData() {
        var snap = NSDiffableDataSourceSnapshot<AnySection, AnyItem>()
        Mock.data.forEach { data in
            snap.appendSections([data.section.eraseToAnySection])
            snap.appendItems(data.items.map(\.eraseToAnyItem))
        }
        dataSource.apply(snap)
    }
  1. Build and run your project.

Start building your dynamic UI collections with ease using AnyLayout!

Releases

No releases published

Packages

No packages published

Languages