Last active
April 22, 2020 17:58
-
-
Save iSapozhnik/73059764c8e814c5bbc9f80cc6ee2393 to your computer and use it in GitHub Desktop.
Creating NSView from XIB file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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