Created
December 15, 2018 12:21
-
-
Save NikhilManapure/d82be13709ef0d9e8bcc49d4a6dbe90a to your computer and use it in GitHub Desktop.
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
import Foundation | |
protocol ReusableView: class { | |
static var identifier: String { get } | |
} | |
extension ReusableView where Self: UIView { | |
static var identifier: 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 UICollectionView { | |
func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView { | |
register(T.self, forCellWithReuseIdentifier: T.identifier) | |
} | |
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.identifier) | |
} | |
func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T where T: ReusableView { | |
guard let cell = dequeueReusableCell(withReuseIdentifier: T.identifier, for: indexPath) as? T else { | |
fatalError("Could not dequeue cell with identifier: \(T.identifier)") | |
} | |
return cell | |
} | |
} | |
extension UITableView { | |
func register<T: UITableViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView { | |
let bundle = Bundle(for: T.self) | |
let nib = UINib(nibName: T.nibName, bundle: bundle) | |
register(nib, forCellReuseIdentifier: T.identifier) | |
} | |
func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T where T: ReusableView { | |
guard let cell = dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as? T else { | |
fatalError("Could not dequeue cell with identifier: \(T.identifier)") | |
} | |
return cell | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment