Using the approach from How to instantiate subclasses of a managed entity in the NSManagedObject Swift extension? you can define a generic helper method that maps the type self from the calling context:
extension UIView { class func instantiateFromNib() -> Self? { return instantiateFromNibHelper() } private class func instantiateFromNibHelper<T>() -> T? { let topLevelObjects = NSBundle.mainBundle().loadNibNamed("CustomViews", owner: nil, options: nil) for topLevelObject in topLevelObjects { if let object = topLevelObject as? T { return object } } return nil } }
This compiles and works as expected in my quick test. If MyCustomView is your subclass of UIView , then
if let customView = MyCustomView.instantiateFromNib() { // `customView` is a `MyCustomView` // ... } else { // Not found in Nib file }
provides an instance of MyCustomView , and the type is automatically displayed.
Update for Swift 3:
extension UIView { class func instantiateFromNib() -> Self? { return instantiateFromNibHelper() } private class func instantiateFromNibHelper<T>() -> T? { if let topLevelObjects = Bundle.main.loadNibNamed("CustomViews", owner: nil, options: nil) { for topLevelObject in topLevelObjects { if let object = topLevelObject as? T { return object } } } return nil } }
Martin R Jul 01 '15 at 16:52 2015-07-01 16:52
source share