Skip to content

Instantly share code, notes, and snippets.

@portellaa
Created November 22, 2016 16:11
Show Gist options
  • Save portellaa/9fb20d7272749aecf996c5b0c0608122 to your computer and use it in GitHub Desktop.
Save portellaa/9fb20d7272749aecf996c5b0c0608122 to your computer and use it in GitHub Desktop.
improved `cellForIndexPath` for UICollectionView and UITableView
protocol TableViewHeaderProtocol: ViewCellReuseIdentifier {
init()
func setupLayout()
}
extension TableViewHeaderProtocol where Self: UITableViewHeaderFooterView {
init() {
self.init(reuseIdentifier: Self.reuseIdentifier)
}
}
extension UICollectionView {
func cellForIndexPath<T: ViewCellProtocol>(indexPath: NSIndexPath) -> T {
guard let cell = self.dequeueReusableCellWithReuseIdentifier(T.reuseIdentifier, forIndexPath: indexPath) as? T else {
assertionFailure("Did you forgot to register cell with identifier `\(T.reuseIdentifier)` for type: `\(T.self)`")
return T()
}
return cell
}
}
extension UITableView {
func cellForIndexPath<T: ViewCellProtocol>(indexPath: NSIndexPath) -> T {
guard let cell = self.dequeueReusableCellWithIdentifier(T.reuseIdentifier, forIndexPath: indexPath) as? T else {
assertionFailure("Did you forgot to register cell with identifier `\(T.reuseIdentifier)` for type: `\(T.self)`")
return T()
}
return cell
}
func headerView<T: BaseTableViewHeaderProtocol>() -> T {
guard let view = self.dequeueReusableHeaderFooterViewWithIdentifier(T.reuseIdentifier) as? T else {
assertionFailure("Did you forgot to register view with identifier `\(T.reuseIdentifier)` for type: `\(T.self)`")
return T()
}
return view
}
}
protocol ViewCellProtocol: ViewCellReuseIdentifier {
init()
func setupLayout()
}
extension ViewCellProtocol where Self: UIView {
init() {
self.init(frame: CGRectZero)
}
}
protocol ViewCellReuseIdentifier {
static var reuseIdentifier: String { get }
}
extension ViewCellReuseIdentifier where Self: UIView {
static var reuseIdentifier: String {
return "\(self)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment