Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UIView extension to simplify load and reuse views
// https://gist.github.com/Koshub/6fb12b8d2430e586b4c8
// Created by Konstantin Gerasimov on 11/25/15.
import UIKit
extension UIView {
class func loadFromNib<T: UIView>(view: T.Type) -> T? {
if let nib = NSBundle.mainBundle().loadNibNamed(className(), owner: nil, options: nil) {
for object in nib {
if let object = object as? T {
return object
}
}
}
return nil
}
}
extension NSObject {
class func className() -> String {
let objectClass: AnyClass = self
let objectClassName = NSStringFromClass(objectClass)
let objectClassNameComponents = objectClassName.componentsSeparatedByString(".")
return objectClassNameComponents.last!
}
}
extension UIStoryboard {
func createViewController<T: UIViewController>(vc: T.Type) -> T {
return instantiateViewControllerWithIdentifier(vc.storyboardId()) as! T
}
}
extension UIViewController {
class func storyboardId() -> String {
return className()
}
}
extension UITableViewCell {
class func cellId() -> String {
return className()
}
}
extension UITableView {
func registerNibOfCell<T: UITableViewCell>(cell: T.Type) {
let nib = UINib(nibName: cell.className(), bundle: nil)
registerNib(nib, forCellReuseIdentifier: cell.cellId())
}
func registerCell<T: UITableViewCell>(cell: T.Type) {
registerClass(cell, forCellReuseIdentifier: cell.cellId())
}
func dequeueReusableCell<T: UITableViewCell>(cell: T.Type = T.self) -> T {
let cell = dequeueReusableCellWithIdentifier(cell.cellId()) as? T
return cell!
}
func dequeueForIndexPath<T: UITableViewCell>(indexPath: NSIndexPath, reusableCell cell: T.Type = T.self) -> T {
let cell = dequeueReusableCellWithIdentifier(cell.cellId(), forIndexPath: indexPath) as? T
return cell!
}
}
extension UICollectionReusableView {
class func viewId() -> String {
return className()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment