Skip to content

Instantly share code, notes, and snippets.

@RichAppz
Created March 15, 2020 10:30
Show Gist options
  • Save RichAppz/a6fe271babebc6d1ed033cb6f6174975 to your computer and use it in GitHub Desktop.
Save RichAppz/a6fe271babebc6d1ed033cb6f6174975 to your computer and use it in GitHub Desktop.
UITableView+Extension
import Foundation
import UIKit
public extension UITableView {
/**
Register nibs faster by passing the type - if for some reason the `identifier` is different then it can be passed
- Parameter type: UITableViewCell.Type
- Parameter identifier: String?
*/
func registerCell(type: UITableViewCell.Type, identifier: String? = nil) {
let cellId = String(describing: type)
register(UINib(nibName: cellId, bundle: nil), forCellReuseIdentifier: identifier ?? cellId)
}
/**
DequeueCell by passing the type of UITableViewCell
- Parameter type: UITableViewCell.Type
*/
func dequeueCell<T: UITableViewCell>(withType type: UITableViewCell.Type) -> T? {
return dequeueReusableCell(withIdentifier: type.identifier) as? T
}
/**
DequeueCell by passing the type of UITableViewCell and IndexPath
- Parameter type: UITableViewCell.Type
- Parameter indexPath: IndexPath
*/
func dequeueCell<T: UITableViewCell>(withType type: UITableViewCell.Type, for indexPath: IndexPath) -> T? {
return dequeueReusableCell(withIdentifier: type.identifier, for: indexPath) as? T
}
}
public extension UITableViewCell {
static var identifier: String {
return String(describing: self)
}
}
@RichAppz
Copy link
Author

RichAppz commented Mar 15, 2020

Registering nibs is simple: tableView.registerCell(type: FooTableViewCell.self)

Also dequeueCell:

guard let cell = tableView.dequeueCell(
     withType: FooTableViewCell.self,
     for: indexPath) as? FooTableViewCell else {
          debugPrint("*** FooTableViewCell is not compiling - fix before deployment ***")
          return UITableViewCell()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment