Skip to content

Instantly share code, notes, and snippets.

@alexj70
Last active April 26, 2017 20:52
Show Gist options
  • Save alexj70/1db1d2d555620ced574cc4bcb6f7cbae to your computer and use it in GitHub Desktop.
Save alexj70/1db1d2d555620ced574cc4bcb6f7cbae to your computer and use it in GitHub Desktop.
Nib loaded

NibLoaded View

import UIKit
protocol NibLoadableView: class {}
extension NibLoadableView where Self: UIView {
    static func fromNib() -> Self {
        return fromNib(nibName: nil)
    }
    
    static func fromNib(nibName: String?) -> Self {
        func fromNibHelper<T>(nibName: String?) -> T where T : UIView {
            let bundle = Bundle(for: T.self)
            let name = nibName ?? String(describing: T.self)
            return bundle.loadNibNamed(name, owner: nil, options: nil)?.first as? T ?? T()
        }
        return fromNibHelper(nibName: nibName)
    }  
}

Using

let view1 = CustomView.fromNib()
let view2: CustomView = UIView.fromNib()
let view3w = CustomView.fromNib("SomeOtherNibFileName")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment