Skip to content

Instantly share code, notes, and snippets.

@JaviSoto
Last active April 14, 2020 11:55
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JaviSoto/6edca1f45a657646211f5b9990583e55 to your computer and use it in GitHub Desktop.
Save JaviSoto/6edca1f45a657646211f5b9990583e55 to your computer and use it in GitHub Desktop.
RSwift Fabric Extensions
import UIKit
import Rswift
struct NibResource: NibResourceType {
let name: String
let bundle: NSBundle
init(name: String, bundle: NSBundle = NSBundle.mainBundle()) {
self.name = name
self.bundle = bundle
}
}
protocol NibInstantiable: class {
associatedtype NibResourceConcreteType: NibResourceType
static var nibResource: NibResourceConcreteType { get }
}
extension NibInstantiable {
static var nib: UINib {
return UINib(
nibName: self.nibResource.name,
bundle: self.nibResource.bundle
)
}
static func instantiateFromNib() -> Self {
return self.nib.instantiateWithOwner(nil, options: nil).first! as! Self
}
}
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