read
I would have expected the process to be similar to iOS equivalence (UIView
), but nope.
Yet I am no longer surprised :D
The Swift Code
To load a view from the nib file requires some code to:
- Load nib from bundle and instantiate
- Add the root view (contentView) to the custom view
- Create constraints to fill the root view (the code uses cartography)
class MyView: NSView {
@IBOutlet var contentView: NSView!
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
setup()
}
private func setup() {
let bundle = Bundle(for: type(of: self))
let nib = NSNib(nibNamed: .init(String(describing: type(of: self))), bundle: bundle)!
nib.instantiate(withOwner: self, topLevelObjects: nil)
addSubview(contentView)
constrain(self, contentView) { view, subview in
subview.edges == view.edges
}
}
}
Setting up the xib
- Create a xib file named the same, that is
MyView.xib
- Set File’s Owner > Class >
MyView
- Connect the root view to the
contentView
IBOutlet
With that, you can create the view programmatically with MyView()
or via Interface Builder.