Last active
October 29, 2016 13:16
-
-
Save desmondmc/574d8e6f5f88625a9f9dbd9d70c3e397 to your computer and use it in GitHub Desktop.
Super CollectionView/TableView nib loading with protocols and generics.
This file contains hidden or 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
// | |
// CollectionViewMagic.swift | |
// bodytonic-ios | |
// | |
// Created by Desmond McNamee on 2016-10-29. | |
// Copyright © 2016 Stadium Studio. All rights reserved. | |
// | |
import UIKit | |
protocol ReusableView: class { | |
static var reuseIdentifier: String { get } | |
} | |
extension ReusableView where Self: UIView { | |
static var reuseIdentifier: String { | |
return String(describing: self) | |
} | |
} | |
protocol NibLoadableView: class { | |
static var nibName: String { get } | |
} | |
extension NibLoadableView where Self: UIView { | |
static var nibName: String { | |
return String(describing: self) | |
} | |
} | |
extension UITableView { | |
func register<T: UITableViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView { | |
self.register(UINib(nibName: T.nibName, bundle: nil), forCellReuseIdentifier: T.reuseIdentifier) | |
} | |
func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView { | |
guard let cell = self.dequeueReusableCell(withIdentifier: T.reuseIdentifier) as? T else { | |
fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)") | |
} | |
return cell | |
} | |
} | |
extension UICollectionView { | |
func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView { | |
register(T.self, forCellWithReuseIdentifier: T.reuseIdentifier) | |
} | |
func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView { | |
let bundle = Bundle(for: T.self) | |
let nib = UINib(nibName: T.nibName, bundle: bundle) | |
register(nib, forCellWithReuseIdentifier: T.reuseIdentifier) | |
} | |
func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView { | |
guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath as IndexPath) as? T else { | |
fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)") | |
} | |
return cell | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment