Reusable
A Swift mixin to use UITableViewCells, UICollectionViewCells and UIViewControllers in a type-safe way, without the need to manipulate their String-typed reuseIdentifiers. This library also supports arbitrary UIView to be loaded via a XIB using a simple call to loadFromNib()
Installation
Requirements: which Reusable version to use for each Swift Version?
| Swift Version |
Reusable Version |
| 2.2 & 2.3 |
2.5.1 |
| 3.0 (†) |
3.0.0 + |
| 4.0 |
4.0.2 + |
| 5.0 |
4.1.0 + |
(†) The Reusable 3.0 code also compiles with Swift 4, you'll need 4.0.2+ only if you're using Carthage for integration
Reusable can be integrated to your Xcode projects using one of the following options:
Installation instructions for Swift Package Manager (SPM)
Swift Package Manager is Apple's decentralized dependency manager to integrate libraries to your Swift projects. It is now fully integrated with Xcode 11
To integrate Reusable into your project using SPM, specify it in your Package.swift file:
let package = Package(
…
dependencies: [
.package(url: "https://github.com/AliSoftware/Reusable.git", from: "4.1.0"),
],
targets: [
.target(name: "YourTarget", dependencies: ["Reusable", …])
…
]
)
Installation instructions for Carthage
Carthage is a decentralized dependency manager to add pre-built frameworks to your Cocoa application.
To integrate Reusable into your Xcode project using Carthage, specify it in your Cartfile:
github "AliSoftware/Reusable"
Then run carthage update --use-xcframeworks
Installation instructions for CocoaPods
CocoaPods is a dependency manager to automate integration of frameworks to your Swift and Objective-C Cocoa projects.
To integrate Reusable into your Xcode project using Cocoapods, specify it in your Podfile:
pod 'Reusable'
Introduction
This library aims to make it super-easy to create, dequeue and instantiate reusable views anywhere this pattern is used: from the obvious UITableViewCell and UICollectionViewCell to custom UIViews, even supporting UIViewControllers from Storyboards.
All of that simply by marking your classes as conforming to a protocol, without having to add any code, and creating a type-safe API with no more String-based API.
// Example of what Reusable allows you to do
final class MyCustomCell: UITableViewCell, Reusable { /* And that's it! */ }
tableView.register(cellType: MyCustomCell.self)
let cell: MyCustomCell = tableView.dequeueReusableCell(for: indexPath)
This concept, called a Mixin (a protocol with default implementation for all its methods), is explained here in my blog post in details.
Table of Contents
Type-safe UITableViewCell / UICollectionViewCell
✍️ Examples and explanations below use UITableView and UITableViewCell, but the exact same examples and explanations apply for UICollectionView and UICollectionViewCell.
1. Declare your cells to conform to Reusable or NibReusable
- Use the
Reusable protocol if they don't depend on a NIB (this will use registerClass(…) to register the cell)
- Use the
NibReusable typealias (= Reusable & NibLoadable) if they use a XIB file for their content (this will use registerNib(…) to register the cell)
final class CustomCell: UITableViewCell, Reusable { /* And that's it! */ }
✍️ Notes
- For cells embedded in a Storyboard's tableView, either one of those two protocols will work (as you won't need to register the cell manually anyway, since registration is handled by the storyboard automatically)
- If you create a XIB-based cell, don't forget to set its Reuse Identifier field in Interface Builder to the same string as the name of the cell class itself.
- 💡
NibReusable is a typealias, so you could still use two protocols conformance Reusable, NibLoadable instead of NibReusable.
📑 Example for a Code-based custom tableView cell
final class CodeBasedCustomCell: UITableViewCell, Reusable {
// By default this cell will have a reuseIdentifier of "CodeBasedCustomCell"
// unless you provide an alternative implementation of `static var reuseIdentifier`
// No need to add anything to conform to Reusable. You can just keep your normal cell code
@IBOutlet private weak var label: UILabel!
func fillWithText(text: String?) { label.text = text }
}
📑 Example for a Nib-based custom tableView cell
final class NibBasedCustomCell: UITableViewCell, NibReusable {
// or
// final class NibBasedCustomCell: UITableViewCell, Reusable, NibLoadable {
// Here we provide a nib for this cell class (which, if we don't override the protocol's
// default implementation of `static var nib: UINib`, will use a XIB of the same name as the class)
// No need to add anything to conform to Reusable. You can just keep your normal cell code
@IBOutlet private weak var pictureView: UIImageView!
func fillWithImage(image: UIImage?) { pictureView.image = image }
}
📑 Example for a Code-based custom collectionView cell
// A UICollectionViewCell which doesn't need a XIB to register
// Either because it's all-code, or because it's registered via Storyboard
final class CodeBasedCollectionViewCell: UICollectionViewCell, Reusable {
// The rest of the cell code goes here
}
📑 Example for a Nib-based custom collectionView cell
// A UICollectionViewCell using a XIB to define it's UI
// And that will need to register using that XIB
final class NibBasedCollectionViewCell: UICollectionViewCell, NibReusable {
// or
// final class NibBasedCollectionViewCell: UICollectionViewCell, Reusable, NibLoadable {
// The rest of the cell code goes here
}
2. Register your cells
Unless you've prototyped your cell in a Storyboard, you'll have to register the cell class or Nib by code.
To do this, instead of calling registerClass(…) or registerNib(…) using a String-based reuseIdentifier, just call:
tableView.register(cellType: theCellClass.self)
📑 Example of `UITableView` registration
class MyViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// This will register using the class (via `register(AnyClass?, forCellReuseIdentifier: String)`)
// because the CodeBasedCustomCell type conforms to Reusable, but not NibLoadable (nor the NibReusable typealias)
tableView.register(cellType: CodeBasedCustomCell.self)
// This will register using NibBasedCustomCell.xib (via `register(UINib?, forCellReuseIdentifier: String)`)
// because the NibBasedCustomCell type conforms to NibLoadable (via the NibReusable typealias)
tableView.register(cellType: NibBasedCustomCell.self)
}
}
3. Dequeue your cells
To dequeue a cell (typically in your cellForRowAtIndexPath implementation), simply call dequeueReusableCell(indexPath:):
// Either
let cell = tableView.dequeueReusableCell(for: indexPath) as MyCustomCell
// Or
let cell: MyCustomCell = tableView.dequeueReusableCell(for: indexPath)
As long as Swift can use type-inference to understand that you'll want a cell of type MyCustomCell (either using as MyCustomCell or explicitly typing the receiving variable cell: MyCustomCell), it will magically infer both the cell class to use and thus its reuseIdentifier needed to dequeue the cell, and which exact type to return to save you a type-cast.
- No need for you to manipulate
reuseIdentifiers Strings manually anymore!
- No need to force-cast the returned
UITableViewCell instance down to your MyCustomCell class either!
📑 Example implementation of `cellForRowAtIndexPath` using `Reusable`
extension MyViewController: UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(indexPath: indexPath) as CodeBasedCustomCell
// Customize the cell here. You can call any type-specific methods here without the need for type-casting
cell.fillWithText("Foo")
return cell
} else {
let cell = tableView.dequeueReusableCell(indexPath: indexPath) as NibBasedCustomCell
// Customize the cell here. no need to downcasting here either!
cell.fillWithImage(UIImage(named:"Bar"))
return cell
}
}
}
Now all you have is a beautiful code and type-safe cells, with compile-type checking, and no more String-based API!
💡 If the cell class you want to dequeue is computed at runtime and stored in a variable, you won't be able to use as theVariable or let cell: theVariable obviously. Instead, you can use the optional parameter cellType (which otherwise gets infered by the return type and is thus not necessary to provide explicitly)
📑 Example with a cell type determined at runtime
class ParentCell: UITableViewCell, Reusable {}
class Child1Cell: ParentCell {}
class Child2Cell: ParentCell {}
func cellType(for indexPath: NSIndexPath) -> ParentCell.Type {
return indexPath.row.isMultiple(of: 2) ? Child1Cell.self : Child2Cell.self
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellClass = self.cellType(for: indexPath)
// As `self.cellType(for:)` always returns a `ParentCell` (sub-)class, the type
// of the variable `cell` below is infered to be `ParentCell` too. So only methods
// declared in the parent `ParentCell` class will be accessible on the `cell` variable.
// But this code will still dequeue the proper type of cell (Child1Cell or Child2Cell).
let cell = tableView.dequeueReusableCell(for: indexPath, cellType: cellClass)
// Then fill the content of your cell (using methods/properties from `ParentCell` type)
return cell
}
Type-safe XIB-based reusable views
Reusable also allows you to create reusable custom views designed in Interface Builder to reuse them in other XIBs or Storyboards, or by code. This allows you to treat those views like custom UI widgets that can be used in multiple places in your app.
1. Declare your views to conform to NibLoadable or NibOwnerLoadable
In your swift source declaring your custom view class:
- Use the
NibLoadable protocol if the XIB you're using don't use its "File's Owner" and the reusable view you're designing is the root view of the XIB
- Use the
NibOwnerLoadable protocol if you used a "File's Owner" of the XIB being of the class of your reusable view, and the root view(s) of the XIB is to be set as a subview providing its content.
// a XIB-based custom UIView, used as root of the XIB
final class NibBasedRootView: UIView, NibLoadable { /* and that's it! */ }
// a XIB-based custom UIView, used as the XIB's "File's Owner"
final class NibBasedFileOwnerView: UIView, NibOwnerLoadable { /* and that's it! */ }
💡 You should use the second approach if you plan to use your custom view in another XIB or Storyboard.
This will allow you to just drop a UIView in a XIB/Storyboard and change its class in IB's inspector to the class of your custom XIB-based view to use it. That custom view will then automagically load its own content from the associated XIB when instantiated by the storyboard containing it, without having to write additional code to load the content of the custom view manually every time.
2. Design your view in Interface Builder
For example if you named your class MyCustomWidget and made it NibOwnerLoadable:
- Set the File's Owner's class to
MyCustomWidget
- Design the content of the view via the root view of that XIB (which is a standard
UIView with no custom class) and its subviews
- Connect any
@IBOutlets and @IBActions between the File's Owner (the MyCustomWidget) and its content
🖼📑 A view configured to be `NibOwnerLoadable`
