Skip to content

Instantly share code, notes, and snippets.

@embassem
Forked from JaviSoto/NibInstantiable.swift
Created April 14, 2020 11:55
Show Gist options
  • Select an option

  • Save embassem/08f04d1621db7fdd1bdc1f14c8fe3945 to your computer and use it in GitHub Desktop.

Select an option

Save embassem/08f04d1621db7fdd1bdc1f14c8fe3945 to your computer and use it in GitHub Desktop.
RSwift Fabric Extensions
import Foundation
import Rswift
protocol ReusableNibTableViewCell: NibInstantiable {
static var reuseIdentifier: IdentifierType { get }
}
extension ReusableNibTableViewCell where NibResourceConcreteType: ReuseIdentifierType, NibResourceConcreteType.ReusableType == Self {
/// Default implementation. Rswift's cell nib structs conform to `ReuseIdentifierType` with an associated type that matches Self
/// So we can know at runtime that this reuse identifier matches this cell, and cells can conform to `ReusableNibTableViewCell` just by
/// conforming to `NibInstantiable`
static var reuseIdentifier: IdentifierType {
return self.nibResource
}
}
import UIKit
import Rswift
extension UITableView {
func registerReusableNibCell<C: ReusableNibTableViewCell where C: UITableViewCell>(_: C.Type) {
self.registerNib(C.nib, forCellReuseIdentifier: C.reuseIdentifier.identifier)
}
}
extension ReusableNibTableViewCell where Self: UITableViewCell {
static func dequeueFromTableView(tableView: UITableView, _ indexPath: NSIndexPath, @noescape configure: (Self -> ()) = { _ in }) -> Self {
let cell = tableView.dequeueReusableCellWithIdentifier(Self.reuseIdentifier.identifier, forIndexPath: indexPath) as! Self
configure(cell)
return cell
}
}
final class SampleTableViewCell: UITableViewCell, ReusableNibTableViewCell {
static let nibResource = R.nib.sampleTableViewCell
}
final class SampleViewController: UIViewController, UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerReusableNibCell(SampleTableViewCell)
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return SampleTableViewCell.dequeueFromTableView(tableView, indexPath) { cell in
/// configure `cell`
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment