Last active
February 18, 2016 22:04
-
-
Save ateliercw/9e2ecc43377ff6cf0cb6 to your computer and use it in GitHub Desktop.
Rough example of improving table view cell registration and dequeuing via generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol AutomaticDequeue { | |
} | |
extension AutomaticDequeue where Self: AnyObject { | |
static var reuseIdentifer: String { | |
return NSStringFromClass(self) as String | |
} | |
} | |
extension UITableView { | |
func registerCellClass<CellClass: UITableViewCell where CellClass: AutomaticDequeue>(cellClass: CellClass.Type) { | |
registerClass(cellClass, forCellReuseIdentifier: cellClass.reuseIdentifer) | |
} | |
func registerHeaderFooterClass<HeaderFooterClass: UITableViewHeaderFooterView where HeaderFooterClass: AutomaticDequeue>(headerFooterClass: HeaderFooterClass.Type) { | |
registerClass(headerFooterClass, forHeaderFooterViewReuseIdentifier: headerFooterClass.reuseIdentifer) | |
} | |
func cellForIndexPath<CellClass: UITableViewCell where CellClass: AutomaticDequeue>(indexPath: NSIndexPath) -> CellClass { | |
guard let cell = dequeueReusableCellWithIdentifier(CellClass.reuseIdentifer, forIndexPath: indexPath) as? CellClass else { | |
fatalError("Could not dequeue cell with identifier \(CellClass.reuseIdentifer)") | |
} | |
return cell | |
} | |
func headerForIndexPath<HeaderFooterClass: UITableViewHeaderFooterView where HeaderFooterClass: AutomaticDequeue>(indexPath: NSIndexPath) -> HeaderFooterClass { | |
guard let header = dequeueReusableHeaderFooterViewWithIdentifier(HeaderFooterClass.reuseIdentifer) as? HeaderFooterClass else { | |
fatalError("Could not dequeue header with identifier \(HeaderFooterClass.reuseIdentifer)") | |
} | |
return header | |
} | |
func footerForIndexPath<HeaderFooterClass: UITableViewHeaderFooterView where HeaderFooterClass: AutomaticDequeue>(indexPath: NSIndexPath) -> HeaderFooterClass { | |
guard let footer = dequeueReusableHeaderFooterViewWithIdentifier(HeaderFooterClass.reuseIdentifer) as? HeaderFooterClass else { | |
fatalError("Could not dequeue footer with identifier \(HeaderFooterClass.reuseIdentifer)") | |
} | |
return footer | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment