Reusable is a Swift µpackage that provides a type-safe way for cell registration and dequeuing in both table and collection views. It is based on this post I wrote a few years ago while I was exploring some of the Swift language features.
To be able to register and reuse a cell or supplementary view in a type-safe way, the view must conform to the ReusableView
protocol:
extension PosterItemCell: ReusableView {}
The default implementation of ReusableView
will provide a reuse identifier based on the class name.
Cells implemented with Interface Builder must also conform to the NibLoadableView
protocol:
extension PosterItemCell: ReusableView, NibLoadableView {}
Once the cell or supplementary view is ready, you can register it in a collection or table view by indicating its type:
func viewDidLoad() {
super.viewDidLoad()
collectionView.register(PosterItemCell.self)
...
}
Likewise, you can dequeue a cell previously registered in this way just by indicating its type:
func collectionView(_: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(PosterItemCell.self, for: indexPath)
...
return cell
}
Using the Swift Package Manager
Add Reusable as a dependency to your Package.swift
file. For more information, see the Swift Package Manager documentation.
.package(url: "https://github.com/gonzalezreal/Reusable", from: "1.0.0")
- Open an issue if you need help, if you found a bug, or if you want to discuss a feature request.
- Open a PR if you want to make some change to
Reusable
. - Contact @gonzalezreal on Twitter.