Skip to content

Instantly share code, notes, and snippets.

@UjwalManjunath
Created November 4, 2015 16:50
Show Gist options
  • Save UjwalManjunath/7267c7226e2bb6254e34 to your computer and use it in GitHub Desktop.
Save UjwalManjunath/7267c7226e2bb6254e34 to your computer and use it in GitHub Desktop.
CollectionViewExtension
import UIKit
extension UICollectionView {
func registerCell(cellType:UICollectionViewCell.Type) {
self.registerNib(cellType.nib(), forCellWithReuseIdentifier: cellType.id())
}
func registerSupplementaryView(classType:UICollectionReusableView.Type, kind:String) {
self.registerNib(classType.nib(), forSupplementaryViewOfKind: kind, withReuseIdentifier: classType.id())
}
func dequeue<T where T:UICollectionViewCell>(cellType:T.Type, indexPath:NSIndexPath) -> T {
self.layer.shouldRasterize = true;
self.layer.rasterizationScale = UIScreen.mainScreen().scale
return self.dequeueReusableCellWithReuseIdentifier(cellType.id(), forIndexPath: indexPath) as! T
}
func dequeueSupplementary<T where T:UICollectionReusableView>(reusableType:T.Type, kind:String, indexPath:NSIndexPath) -> T {
return self.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: reusableType.id(), forIndexPath: indexPath) as! T
}
}
extension UICollectionReusableView {
class func nib() -> UINib {
var className = NSStringFromClass(self)
if let range = className.rangeOfString(".") {
className = className.substringFromIndex(range.endIndex)
}
return UINib(nibName: className, bundle: NSBundle.mainBundle())
}
class func id() -> String {
var className = NSStringFromClass(self)
if let range = className.rangeOfString(".") {
className = className.substringFromIndex(range.endIndex)
} else {
print("Found a mangled class name? \(className)")
}
return className
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment