Skip to content

Instantly share code, notes, and snippets.

@iSapozhnik
Last active April 22, 2020 17:58
Show Gist options
  • Save iSapozhnik/73059764c8e814c5bbc9f80cc6ee2393 to your computer and use it in GitHub Desktop.
Save iSapozhnik/73059764c8e814c5bbc9f80cc6ee2393 to your computer and use it in GitHub Desktop.
Creating NSView from XIB file
// For views that can be loaded from nib file
protocol NibLoadable {
// Name of the nib file
static var nibName: String { get }
static func createFromNib(in bundle: Bundle) -> Self
}
extension NibLoadable where Self: NSView {
// Default nib name must be same as class name
static var nibName: String {
return String(describing: Self.self)
}
static func createFromNib(in bundle: Bundle = Bundle.main) -> Self {
var topLevelArray: NSArray? = nil
bundle.loadNibNamed(NSNib.Name(nibName), owner: self, topLevelObjects: &topLevelArray)
let views = Array<Any>(topLevelArray!).filter { $0 is Self }
return views.last as! Self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment