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()
Reusable can be integrated to your Xcode projects using one of the following options:
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
UITableViewCell
/ UICollectionViewCell
✍️ Examples and explanations below use
UITableView
andUITableViewCell
, but the exact same examples and explanations apply forUICollectionView
andUICollectionViewCell
.
Reusable
or NibReusable
Reusable
protocol if they don't depend on a NIB (this will use registerClass(…)
to register the cell)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 conformanceReusable, NibLoadable
instead ofNibReusable
.
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)
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.
reuseIdentifiers
Strings manually anymore!UITableViewCell
instance down to your MyCustomCell
class either!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
orlet cell: theVariable
obviously. Instead, you can use the optional parametercellType
(which otherwise gets infered by the return type and is thus not necessary to provide explicitly)📑 Example with a cell type determined at runtime
```swift 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 } ```
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.
NibLoadable
or NibOwnerLoadable
In your swift source declaring your custom view class:
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 XIBNibOwnerLoadable
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.
For example if you named your class MyCustomWidget
and made it NibOwnerLoadable
:
MyCustomWidget
UIView
with no custom class) and its subviews@IBOutlets
and @IBActions
between the File's Owner (the MyCustomWidget
) and its contentThen that widget can be integrated in a Storyboard Scene (or any other XIB) by simply dropping a UIView
on the Storyboard, and changing its class to MyCustomWidget
in IB's inspector.
NibOwnerLoadable
viewIf you used NibOwnerLoadable
and made your custom view the File's Owner of your XIB, you should then override init?(coder:)
so that it loads it's associated XIB as subviews and add constraints automatically:
final class MyCustomWidget: UIView, NibOwnerLoadable {
…
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.loadNibContent()
}
}
self.loadNibContent()
is a method provided by the NibOwnerLoadable
mixin. It basically loads the content from the associated MyCustomWidget.xib
, then add all the root views in that XIB as subviews of your MyCustomWidget
, with appropriate layout constraints to make them the same size as your MyCustomWidget
container view.
Overriding init?(coder:)
and calling self.loadNibContent()
thus allows you to have that content automatically loaded by the system when that MyCustomWidget
in included in another XIB or in a Storyboard (as init?(coder:)
is the init
that is called by iOS to create those instances in a XIB or Storyboard)
💡 Note: it is also possible to override init(frame:)
similarly, in order to be able to also create an instance of that view manually via code if needed.
NibLoadable
viewIf you used NibLoadable
and made your custom view the root view of your XIB (not using the File's Owner at all), these are not designed to be used in other Storyboards or XIBs like NibOwnerLoadable
is, as they won't be able to auto-load their content.
Instead, you will instantiate those NibLoadable
views by code, which is as simple as calling loadFromNib()
on your custom class:
let view1 = NibBasedRootView.loadFromNib() // Create one instance
let view2 = NibBasedRootView.loadFromNib() // Create another one
let view3 = NibBasedRootView.loadFromNib() // and another one
…
Reusable
also allows you to mark your UIViewController
classes as StoryboardBased
or StoryboardSceneBased
to easily instantiate them from their associated Storyboard in a type-safe way.
UIViewController
to conform to StoryboardBased
or StoryboardSceneBased
In your swift source declaring your custom UIViewController
class:
StoryboardBased
protocol if the *.storyboard
file has the same name as the ViewController's class, and its scene is the "initial scene" of the storyboard.
StoryboardSceneBased
protocol if scene in your storyboard has the same sceneIdentifier
as the name of the ViewController's class, but the *.storyboard
file name doesn't necessary match the ViewController's class name.
sceneStoryboard
type property to indicate the storyboard it belongs to.Simply call instantiate()
on your custom class. This will automatically know which storyboard to load it from, and which scene (initial or not) to use to instantiate it.
func presentSecondary() {
let vc = SecondaryVC.instantiate() // Init from the "SecondaryVC" scene of CustomVC.storyboard
self.present(vc, animated: true) {}
}
final
I advise you to mark your custom UITableViewCell
, UICollectionViewCell
, UIView
and UIViewController
subclasses as being final
. This is because:
protocols
that have Self
requirements, like the ones used by this pod (Reusable
, StoryboardBased
, …). In some cases you can avoid making your classes final
, but in general it's a good practice, and in the case of this pod, usually your custom UIViewController
or whatever won't be subclassed anyway:
final
makes sense hereUIViewController
, UITableViewCell
, etc… is intended to be subclassed and be the parent class of many classes in your app, it makes more sense to add the protocol conformance (StoryboardBased
, Reusable
, …) to the child classes (and mark them final
) than adding the protocol on the parent, abstract class.The protocols in this pod, like Reusable
, NibLoadable
, NibOwnerLoadable
, StoryboardBased
, NibReusable
… are what is usually called Mixins, which basically is a Swift protocol with a default implementation provided for all of its methods.
The main benefit is that you don't need to add any code: just conform to Reusable
, NibOwnerLoadable
or any of those protocol and you're ready to go with no additional code to write.
But of course, those provided implementations are just default implementations. That means that if you need you can still provide your own implementations in case for some reason some of your cells don't follow the classic configuration of using the same name for both the class, the reuseIdentifier
and the XIB file.
final class VeryCustomNibBasedCell: UITableViewCell, NibReusable {
// This cell use a non-standard configuration: its reuseIdentifier and XIB file
// have a different name as the class itself. So we need to provide a custom implementation or `NibReusable`
static var reuseIdentifier: String { return "VeryCustomReuseIdentifier" }
static var nib: UINib { return UINib(nibName: "VeryCustomUI", bundle: nil) } // Use VeryCustomUI.xib
// Then continue with the rest of your normal cell code
}
The same is true for all the protocols of this pod, which always provide default implementations which could still be replaced by your own if you need some custom cases.
But the beauty is in 90% of cases the default implementation will match typical conventions and the default implementations will be exactly what you want!
fatalError
Reusable
allows you to manipulate type-safe APIs and make you avoid typos. But things could still go wrong in case of a misconfguration, for example if you forgot to set the reuseIdentifier
of your cell in its XIB
, or you declared a FooViewController
to be StoryboardBased
but forgot to set the initial ViewController flag on that FooViewController
scene in that Storyboard, etc.
In such cases, because those are developer errors that should be caught as early as possible in the development process, Reusable
will call fatalError
with an error message as descriptive as possible (instead of crashing with an obscure message about some force-cast or force-unwrap or whatnot) to help you configure it right.
For example, if Reusable
fails to dequeue a cell, it will bail with a message like:
« Failed to dequeue a cell with identifier \(cellType.reuseIdentifier) matching type \(cellType.self). Check that the reuseIdentifier is set properly in your XIB/Storyboard and that you registered the cell beforehand. »
Hopefully, those explicit failure messages will allow you to understand what was misconfigured and help you fix it!
This repository comes with an example project in the Example/
folder. Feel free to try it.
It demonstrates how Reusable
works for:
UITableViewCell
and UICollectionViewCell
subclasses,UICollectionView
's SupplementaryViews
(section Headers)UIView
designed in a XIB (NibOwnerLoadable
)The concepts behind Reusable has been presented in various articles and talks:
This code is distributed under the MIT license. See the LICENSE
file for more info.