Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create generic table/collection controllers #70

Open
tylermilner opened this issue Aug 21, 2019 · 0 comments
Open

Create generic table/collection controllers #70

tylermilner opened this issue Aug 21, 2019 · 0 comments

Comments

@tylermilner
Copy link
Contributor

I know most of our projects typically separate out table/collection view functionality into separate objects. We should take this a step further and make some generic controllers to handle this (which I think some projects already do). Since SwiftUI is coming (eventually), we shouldn't spend too much time on it, but at least handling the basic case of presenting a list of identical cells should be a goal.

I spent a few minutes doodling so here's something to get started:

class CollectionController<ItemType, CellType: UICollectionViewCell>: NSObject, UICollectionViewDataSource {
    
    private let items: [ItemType]
    private let cellConfigurationBlock: (ItemType, CellType) -> Void
    
    init(items: [ItemType], cellConfigurationBlock: @escaping (ItemType, CellType) -> Void) {
        self.items = items
        self.cellConfigurationBlock = cellConfigurationBlock
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CellType.self), for: indexPath) as? CellType else { fatalError("Unable to dequeue cell of type '\(CellType.self)'") }
        
        let item = items[indexPath.item]
        cellConfigurationBlock(item, cell)
        
        return cell
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant