Skip to content

Instantly share code, notes, and snippets.

@stevethomp
Last active October 5, 2016 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevethomp/7583462b046efe6ad415f36b6c4d9893 to your computer and use it in GitHub Desktop.
Save stevethomp/7583462b046efe6ad415f36b6c4d9893 to your computer and use it in GitHub Desktop.
Simplifies the UITableView cell methods that are called all the time, and does away with annoying force unwraps in ViewControllers.
import UIKit
public extension UICollectionView {
public func register<T: UICollectionViewCell>(type: T.Type) {
registerNib(T.Nib, forCellWithReuseIdentifier: T.Identifier)
}
public func cell<T: UICollectionViewCell>(forIndexPath indexPath: NSIndexPath) -> T {
return dequeueReusableCellWithReuseIdentifier(T.Identifier, forIndexPath: indexPath) as! T
}
public func register<T: UICollectionReusableView>(type: T.Type, forSupplementaryViewOfKind kind: String) {
registerNib(T.Nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: T.Identifier)
}
public func supplementaryView<T: UICollectionReusableView>(ofKind kind: String, forIndexPath indexPath: NSIndexPath) -> T {
return dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: T.Identifier, forIndexPath: indexPath) as! T
}
}
/* With these extensions, all you need to do to register a nib is:
/
/ tableView.register(CustomCell.self)
/
/ And to dequeue, just call:
/
/ let cell: CustomCell = tableView.cell(forIndexPath: indexPath)
/
/ No string constants, no repeating cell class, and no pesky 'as!'
*/
import UIKit
public extension UITableView {
public func register<T: UITableViewCell>(type: T.Type) {
registerNib(T.Nib, forCellReuseIdentifier: T.Identifier)
}
public func cell<T: UITableViewCell>(forIndexPath indexPath: NSIndexPath) -> T {
return dequeueReusableCellWithIdentifier(T.Identifier, forIndexPath: indexPath) as! T
}
public func register<T: UITableViewHeaderFooterView>(type: T.Type) {
registerNib(T.Nib, forHeaderFooterViewReuseIdentifier: T.Identifier)
}
public func headerFooterView<T: UITableViewHeaderFooterView>() -> T {
return dequeueReusableHeaderFooterViewWithIdentifier(T.Identifier) as! T
}
}
// Easy access to Nib and Identifier, provided you always name Identifier the same as class
import UIKit
public extension UIView {
public static var Nib: UINib {
let bundle = NSBundle(forClass: self)
return UINib(nibName: Identifier, bundle: bundle)
}
public static var Identifier: String {
return String(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment