You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

465 lines
22 KiB

5 years ago
  1. # Reusable
  2. <p align="center">
  3. <img alt="Reusable" src="Logo.png" width="150" height="150"/>
  4. </p>
  5. 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()`
  6. [![CircleCI](https://circleci.com/gh/AliSoftware/Reusable/tree/master.svg?style=svg)](https://circleci.com/gh/AliSoftware/Reusable/tree/master)
  7. [![Platform](http://cocoapod-badges.herokuapp.com/p/Reusable/badge.png)](http://cocoadocs.org/docsets/Reusable)
  8. [![Version](http://cocoapod-badges.herokuapp.com/v/Reusable/badge.png)](http://cocoadocs.org/docsets/Reusable)
  9. [![Language: Swift 3 & 4](https://img.shields.io/badge/Swift-3%20%26%204-orange.svg)](https://swift.org)
  10. # Requirements
  11. | Swift Version | Reusable Version |
  12. |----------------|--------------------|
  13. | 2.2 & 2.3 | 2.5.1 |
  14. | 3.0 (†) | 3.0.0 + |
  15. | 4.0 | 4.0.2 + |
  16. _(†) The Reusable 3.0 code also compiles with Swift 4, you'll need 4.0.2+ only if you're using Carthage for integration_
  17. # Introduction
  18. 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.
  19. 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**.
  20. ```swift
  21. // Example of what Reusable allows you to do
  22. final class MyCustomCell: UITableViewCell, Reusable { /* And that's it! */ }
  23. tableView.register(cellType: MyCustomCell.self)
  24. let cell: MyCustomCell = tableView.dequeueReusableCell(for: indexPath)
  25. ```
  26. This concept, called a [Mixin](http://alisoftware.github.io/swift/protocol/2015/11/08/mixins-over-inheritance/) (a protocol with default implementation for all its methods), is explained [here in my blog post](http://alisoftware.github.io/swift/generics/2016/01/06/generic-tableviewcells/) in details.
  27. **Table of Contents**
  28. * [Type-safe cells](#type-safe-uitableviewcell--uicollectionviewcell)
  29. * [Type-safe XIB-based reusable views](#type-safe-xib-based-reusable-views)
  30. * [Type-safe ViewControllers from Storyboards](#type-safe-viewcontrollers-from-storyboards)
  31. * [Additional tips](#additional-tips)
  32. * [Example project](#example-project)
  33. * [Talks and Articles about Reusable](#talks-and-articles-about-reusable)
  34. * [License](#license)
  35. ---
  36. # Type-safe `UITableViewCell` / `UICollectionViewCell`
  37. > ✍️ Examples and explanations below use `UITableView` and `UITableViewCell`, but the exact same examples and explanations apply for `UICollectionView` and `UICollectionViewCell`.
  38. ## 1. Declare your cells to conform to `Reusable` or `NibReusable`
  39. * Use the `Reusable` protocol if they don't depend on a NIB (this will use `registerClass(…)` to register the cell)
  40. * Use the `NibReusable` typealias (= `Reusable & NibLoadable`) if they use a `XIB` file for their content (this will use `registerNib(…)` to register the cell)
  41. ```swift
  42. final class CustomCell: UITableViewCell, Reusable { /* And that's it! */ }
  43. ```
  44. > ✍️ **Notes**
  45. >
  46. > * For cells embedded in a Storyboard's tableView, either one of those two protocols will work (as you won't register the cell them manually anyway)
  47. > * 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.
  48. > * 💡 `NibReusable` is a typealias, so you could still use two protocols conformance `Reusable, NibLoadable` instead of `NibReusable`.
  49. <details>
  50. <summary>📑 Example for a Code-based custom tableView cell</summary>
  51. ```swift
  52. final class CodeBasedCustomCell: UITableViewCell, Reusable {
  53. // By default this cell will have a reuseIdentifier of "CodeBasedCustomCell"
  54. // unless you provide an alternative implementation of `var reuseIdentifier`
  55. // No need to add anything to conform to Reusable. You can just keep your normal cell code
  56. @IBOutlet private weak var label: UILabel!
  57. func fillWithText(text: String?) { label.text = text }
  58. }
  59. ```
  60. </details>
  61. <details>
  62. <summary>📑 Example for a Nib-based custom tableView cell</summary>
  63. ```swift
  64. final class NibBasedCustomCell: UITableViewCell, NibReusable {
  65. // or
  66. // final class NibBasedCustomCell: UITableViewCell, Reusable, NibLoadable {
  67. // Here we provide a nib for this cell class (which, if we don't override the protocol's
  68. // default implementation of `nib`, will use a XIB of the same name as the class)
  69. // No need to add anything to conform to Reusable. You can just keep your normal cell code
  70. @IBOutlet private weak var pictureView: UIImageView!
  71. func fillWithImage(image: UIImage?) { pictureView.image = image }
  72. }
  73. ```
  74. </details>
  75. <details>
  76. <summary>📑 Example for a Code-based custom collectionView cell</summary>
  77. ```swift
  78. // A UICollectionViewCell which doesn't need a XIB to register
  79. // Either because it's all-code, or because it's registered via Storyboard
  80. final class CodeBasedCollectionViewCell: UICollectionViewCell, Reusable {
  81. // The rest of the cell code goes here
  82. }
  83. ```
  84. </details>
  85. <details>
  86. <summary>📑 Example for a Nib-based custom collectionView cell</summary>
  87. ```swift
  88. // A UICollectionViewCell using a XIB to define it's UI
  89. // And that will need to register using that XIB
  90. final class NibBasedCollectionViewCell: UICollectionViewCell, NibReusable {
  91. // or
  92. // final class NibBasedCollectionViewCell: UICollectionViewCell, Reusable, NibLoadable {
  93. // The rest of the cell code goes here
  94. }
  95. ```
  96. </details>
  97. ## 2. Register your cells
  98. Unless you've prototyped your cell in a Storyboard, you'll have to register the cell class or Nib by code.
  99. To do this, instead of calling `registerClass(…)` or `registerNib(…)` using a String-based `reuseIdentifier`, just call:
  100. ```swift
  101. tableView.register(cellType: theCellClass.self)
  102. ```
  103. <details>
  104. <summary>📑 Example of `UITableView` registration</summary>
  105. ```swift
  106. class MyViewController: UIViewController {
  107. @IBOutlet private weak var tableView: UITableView!
  108. override func viewDidLoad() {
  109. super.viewDidLoad()
  110. tableView.register(cellType: CodeBasedCustomCell.self) // This will register using the class without using a UINib
  111. tableView.register(cellType: NibBasedCustomCell.self) // This will register using NibBasedCustomCell.xib
  112. }
  113. }
  114. ```
  115. </details>
  116. ## 3. Dequeue your cells
  117. To dequeue a cell (typically in your `cellForRowAtIndexPath` implementation), simply call `dequeueReusableCell(indexPath:)`:
  118. ```swift
  119. // Either
  120. let cell = tableView.dequeueReusableCell(for: indexPath) as MyCustomCell
  121. // Or
  122. let cell: MyCustomCell = tableView.dequeueReusableCell(for: indexPath)
  123. ```
  124. As long as **Swift can use type-inference to understand that you'll want a cell of type `MyCustomCell`** (either using `as MyCystomCell` 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.
  125. * No need for you to manipulate `reuseIdentifiers` Strings manually anymore!
  126. * No need to force-cast the returned `UITableViewCell` instance down to your `MyCustomCell` class either!
  127. <details>
  128. <summary>📑 Example implementation of `cellForRowAtIndexPath` using `Reusable`</summary>
  129. ```swift
  130. extension MyViewController: UITableViewDataSource {
  131. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  132. if indexPath.section == 0 {
  133. let cell = tableView.dequeueReusableCell(indexPath: indexPath) as CodeBasedCustomCell
  134. // Customize the cell here. You can call any type-specific methods here without the need for type-casting
  135. cell.fillWithText("Foo")
  136. return cell
  137. } else {
  138. let cell = tableView.dequeueReusableCell(indexPath: indexPath) as NibBasedCustomCell
  139. // Customize the cell here. no need to downcasting here either!
  140. cell.fillWithImage(UIImage(named:"Bar"))
  141. return cell
  142. }
  143. }
  144. }
  145. ```
  146. </details>
  147. Now all you have is **a beautiful code and type-safe cells**, with compile-type checking, and no more String-based API!
  148. > 💡 If the cell class is computed at runtime in a variable, you won't be able to use `as theVariable` or `let cell: theVariable` obviously… but instead you can use the optional parameter `cellType` (which otherwise gets infered by the return type and is thus not necessary to provide explicitly)
  149. >
  150. > <details>
  151. > <summary>📑 Example with a cell type determined at runtime</summary>
  152. >
  153. > ```swift
  154. > class ParentCell: UITableViewCell, Reusable {}
  155. > class Child1Cell: ParentCell {}
  156. > class Child2Cell: ParentCell {}
  157. >
  158. > func cellType(for indexPath: NSIndexPath) -> ParentCell.Type {
  159. > return (indexPath.row % 2 == 0) ? Child1Cell.self : Child2Cell.self
  160. > }
  161. >
  162. > func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  163. > let cellClass = self.cellType(for: indexPath)
  164. > // As `self.cellType(for:)` always returns a `ParentCell` (sub-)class, the type
  165. > // of the variable `cell` below is infered to be `ParentCell` too. So only methods
  166. > // declared in the parent `ParentCell` class will be accessible on the `cell` variable.
  167. > let cell = tableView.dequeueReusableCell(for: indexPath, cellType: cellClass)
  168. > return cell
  169. > }
  170. > ```
  171. > </details>
  172. ---
  173. # Type-safe XIB-based reusable views
  174. `Reusable` also allows you to create reusable custom views designed in Interface Builder to reuse them in other XIBs or by code, like creating custom UI widgets used in multiple places in your app.
  175. ## 1. Declare your views to conform to `NibLoadable` or `NibOwnerLoadable`
  176. In your swift source declaring your custom view class:
  177. * 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
  178. * 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.
  179. ```swift
  180. // a XIB-based custom UIView, used as root of the XIB
  181. final class NibBasedRootView: UIView, NibLoadable { /* and that's it! */ }
  182. // a XIB-based custom UIView, used as the XIB's "File's Owner"
  183. final class NibBasedFileOwnerView: UIView, NibOwnerLoadable { /* and that's it! */ }
  184. ```
  185. > 💡 You should use the second approach if you plan to use your custom view in another XIB or Storyboard.
  186. > This will allow you to just drop a UIView in a XIB/Storyboard and change its class 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.
  187. ## 2. Design your view in Interface Builder
  188. For example if you named your class `MyCustomWidget` and made it `NibOwnerLoadable`:
  189. * Set the _File's Owner_'s class to `MyCustomWidget`
  190. * 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
  191. * Connect any `@IBOutlets` and `@IBActions` between the _File's Owner_ (the `MyCustomWidget`) and its content
  192. <details>
  193. <summary>🖼📑 A view configured to be `NibOwnerLoadable`</summary>
  194. ![NibOwnerLoadable view in Interface Builder](NibOwnerLoadable.png)
  195. ```swift
  196. final class MyCustomWidget: UIView, NibOwnerLoadable {
  197. @IBOutlet private var rectView: UIView!
  198. @IBOutlet private var textLabel: UILabel!
  199. @IBInspectable var rectColor: UIColor? {
  200. didSet {
  201. self.rectView.backgroundColor = self.rectColor
  202. }
  203. }
  204. @IBInspectable var text: String? {
  205. didSet {
  206. self.textLabel.text = self.text
  207. }
  208. }
  209. }
  210. ```
  211. </details>
  212. Then 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`.
  213. <details>
  214. <summary>🖼 Example of a `NibOwnerLoadable` custom view once integrated in another Storyboard</summary>
  215. * In the capture below, all blue square views have a custom class of `MyCustomWidget` set in Interface Builder.
  216. * When selecting one of this custom class, you have direct access to all `@IBOutlet` that this `MyCustomWidget` exposes, which allows you to connect them to other views of the Storyboard if needed
  217. * When selecting one of this custom class, you also have access to all the `@IBInspectable` properties. For example, in the capture below, you can see the "Rect color" and "Text" inspectable properties on the right panel, that you can change right from the Storyboard integrating your custom widget.
  218. ![NibOwnerLoadable integrated in a Storyboard](NibOwnerLoadable-InStoryboard.png)
  219. </details>
  220. ## 3a. Auto-loading the content of a `NibOwnerLoadable` view
  221. If you used `NibOwnerLoadable` and made your custom view the File's Owner of your XIB, you should then override `init?(coder:)` so that it load it's associated XIB as subviews and add constraints automatically:
  222. ```swift
  223. final class MyCustomWidget: UIView, NibOwnerLoadable {
  224. required init?(coder aDecoder: NSCoder) {
  225. super.init(coder: aDecoder)
  226. self.loadNibContent()
  227. }
  228. }
  229. ```
  230. Overriding `init?(coder:)` allows your `MyCustomWidget` custom view to load its content from the associated XIB `MyCustomWidget.xib` and add it as subviews of itself.
  231. _💡 Note: it is also possible to override `init(frame:)`, in order to be able to create an instance of that view programatically and call `loadNibContent()` to fill with views if needed._
  232. ## 3b. Instantiating a `NibLoadable` view
  233. If 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.
  234. Instead, you will instantiate those `NibLoadable` views by code, which is as simple as calling `loadFromNib()` on your custom class:
  235. ```swift
  236. let view1 = NibBasedRootView.loadFromNib() // Create one instance
  237. let view2 = NibBasedRootView.loadFromNib() // Create another one
  238. let view3 = NibBasedRootView.loadFromNib() // and another one
  239. ```
  240. ---
  241. # Type-safe ViewControllers from Storyboards
  242. `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.
  243. ## 1. Declare your `UIViewController` to conform to `StoryboardBased` or `StoryboardSceneBased`
  244. In your swift source declaring your custom `UIViewController` class:
  245. * Use the `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.
  246. * This is typically ideal if you use one Storyboard per ViewController, for example.
  247. * Use the `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.
  248. * This is typically ideal for secondary scenes in bigger storyboards
  249. * You'll then be required to implement the `sceneStoryboard` type property to indicate the storyboard it belongs to.
  250. <details>
  251. <summary>📑 Example of a ViewController being the initial ViewController of its Storyboard</summary>
  252. In this example, `CustomVC` is designed as the initial ViewController of a Storyboard named `CustomVC.storyboard`:
  253. ```swift
  254. final class CustomVC: UIViewController, StoryboardBased { /* and that's it! */ }
  255. ```
  256. </details>
  257. <details>
  258. <summary>📑 Example of a ViewController being an arbitrary scene in a differently-named Storyboard</summary>
  259. In this example, `SecondaryVC` is designed in a Storyboard name `CustomVC.storyboard` (so with a different name than the class itself) and is _not_ the initial ViewController, but instead has its **"Scene Identifier"** set to the value `"SecondaryVC"` (same as the class name)
  260. Conforming to `StoryboardSceneBased` will still require you to implement `static var sceneStoryboard: UIStoryboard { get }` to indicate the Storyboard where this scene is designed. You can typically implement that property using a `let` type constant:
  261. ```swift
  262. final class SecondaryVC: UIViewController, StoryboardSceneBased {
  263. static let sceneStoryboard = UIStoryboard(name: "CustomVC", bundle: nil)
  264. /* and that's it! */
  265. }
  266. ```
  267. </details>
  268. ## 2. Instantiate your UIViewControllers
  269. 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.
  270. ```swift
  271. func presentSecondary() {
  272. let vc = SecondaryVC.instantiate() // Init from the "SecondaryVC" scene of CustomVC.storyboard
  273. self.present(vc, animated: true) {}
  274. }
  275. ```
  276. ---
  277. # Additional tips
  278. ## Make your subclasses `final`
  279. I advise you to mark your custom `UITableViewCell`, `UICollectionViewCell`, `UIView` and `UIViewController` subclasses as being `final`. This is because:
  280. * In most cases, the custom cells and VCs you plan to instantiate are not intended to be subclassed themselves.
  281. * More importantly, it helps the compiler a lot and gives you big optimizations
  282. * It can be required in some cases when conforming to `protocols` that have `Self` requirements, like the ones used by this pod (`Reusable`, `StoryboardBased`, …).
  283. 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:
  284. * Either they are intended to be used and instantiated directly and never be subclassed, so `final` makes sense here
  285. * In case your custom `UIViewController`, `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.
  286. ## Customize reuseIdentifier, nib, etc for non-conventional uses
  287. The protocols in this pod, like `Reusable`, `NibLoadable`, `NibOwnerLoadable`, `StoryboardBased`, `NibReusable`… are what is usually called [Mixins](http://alisoftware.github.io/swift/protocol/2015/11/08/mixins-over-inheritance/), which basically is a Swift protocol with a default implementation provided for all of its methods.
  288. 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.
  289. 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.
  290. ```swift
  291. final class VeryCustomNibBasedCell: UITableViewCell, NibReusable {
  292. // This cell use a non-standard configuration: its reuseIdentifier and XIB file
  293. // have a different name as the class itself. So we need to provide a custom implementation or `NibReusable`
  294. static var reuseIdentifier: String { return "VeryCustomReuseIdentifier" }
  295. static var nib: UINib { return UINib(nibName: "VeryCustomUI", bundle: nil) } // Use VeryCustomUI.xib
  296. // Then continue with the rest of your normal cell code
  297. }
  298. ```
  299. 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.
  300. _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!_
  301. ## Type-safety and `fatalError`
  302. `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.
  303. 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.
  304. For example, if `Reusable` fails to dequeue a cell, it will bail with a message like:
  305. > « Failed to dequeue a cell with identifier \\(cellType.reuseIdentifier) matching type \\(cellType.self).
  306. > Check that the reuseIdentifier is set properly in your XIB/Storyboard and that you registered the cell beforehand. »
  307. Hopefully, those explicit failure messages will allow you to understand what was misconfigured and help you fix it!
  308. ---
  309. # Example Project
  310. This repository comes with an example project in the `Example/` folder. Feel free to try it.
  311. It demonstrates how `Reusable` works for:
  312. * `UITableViewCell` and `UICollectionViewCell` subclasses,
  313. * Cells whose UI template is either only provided by plain code, or provided by a XIB, or prototyped directly in a Storyboard.
  314. * `UICollectionView`'s `SupplementaryViews` (section Headers)
  315. * Custom `UIView` designed in a XIB (`NibOwnerLoadable`)
  316. # Talks and Articles about Reusable
  317. The concepts behind Reusable has been presented in various articles and talks:
  318. * [Using Generics to improve TableView cells](https://alisoftware.github.io/swift/generics/2016/01/06/generic-tableviewcells/) on my blog
  319. * [FrenchKit'16 talk: Mixins over Inheritance](https://youtu.be/BSn4jlunn4I) (video)
  320. * Same talk was also given at NSSpain'16 ([slides](https://speakerdeck.com/alisoftware/mixins-over-inheritance)) and AppDevCon'17 ([slides](https://speakerdeck.com/alisoftware/mixins-over-inheritance-appdevcon-17))
  321. # License
  322. This code is distributed under the MIT license. See the `LICENSE` file for more info.