I have watched numerous tutorials on how to create a custom View in Interface Builder. All are for iOS but MacOS should be similar, no? I have tried a few methods but none are completely successful. The init(coder:)
calls the NIB instantiation (either through Bundle.main.loadNibNamed
or NSNib
which, in turn, calls init(coder:)
and ends up with infinite recursion if I class the main view in my nib as my custom class
If I use a standard class then make file's owner my custom class that works better but still isn't right.
Is there an example that creates a custom control, using AppKit, that works? The closest that I have come displays the custom control but none of the autolayout settings work.
It must be fairly simple but I haven't figured it out yet.
Here is what I have so far:
- A new class MyControl
import Cocoa
@IBDesignable
class MyControl: NSView {
@IBOutlet var customView: NSView! // The top level NSView
@IBOutlet weak var insideButton: NSButton! // The button inside the view
let myName: String
required init?(coder: NSCoder) {
super.init(coder: coder)
if Bundle.main.loadNibNamed("MyControl", owner: self, topLevelObjects: nil) {
addSubview(customView)
}
}
}
A nib based on NSView with contains a centered NSButton. The
File's Owner
class is set toMyControl
, the top level view remains asNSView
The
Main.storyboard
has a Custom View classed asMyControl
centered with height and width set.
When I view Main.storyboard
it has a frame for the custom view but it is blank.
When I run the application the window that displays is blank.