Skip to content

Instantly share code, notes, and snippets.

@xxKRASHxx
Last active December 8, 2017 16:48
Show Gist options
  • Save xxKRASHxx/17502c94cd847e97f1fc4effbfb495ff to your computer and use it in GitHub Desktop.
Save xxKRASHxx/17502c94cd847e97f1fc4effbfb495ff to your computer and use it in GitHub Desktop.
Generic protocol for loading views from xib
import UIKit
class AnyViewClass: UIView {}
extension AnyView: NibInstantiable { }
let view: AnyViewClass = .fromNib()
type(of: view) //will be AnyViewClass
import Foundation
import UIKit
public protocol NibInstantiatable: class {}
public extension UIView {
public static func fromNib<AnyView>() -> AnyView
where AnyView: NibInstantiatable {
guard let view = self.nib
.instantiate(withOwner: nil, options: nil)
.first as? AnyView else { fatalError("Can not load \(AnyView.self) from xib") }
return view
}
public static var nib: UINib {
return UINib(
nibName: identifier,
bundle: Bundle(for: self)
)
}
public static var identifier: String {
return String(describing: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment