Search code examples
swiftmacosnsviewnsviewcontroller

Where to ctrl-drag IBOutlets, view class or ViewController?


I'm pretty new to coding. Im not sure if an IBOutlet (button, text field, etc) ctrl-dragged from a xib should go in the xib's NSView class or in the view controller which has the NSView added as a subview.

I've been playing around with this for a while, learning as I go. I'm stuck on wondering if I have the code structured correctly. This is for MacOS so resources are limited and often dated. I'd assume that an outlet added for a button, for example, would go in the controller as views should be "dumb". If I try that the actions always have "action" set automatically and type as Any as a default - not what I'm used to seeing. I suspect this may have something to do with the class set for the file's owner and the class set for the view in IB. If anyone can outline the best way to handle this that would be fantastic, thank you!

The view that loads the xib:

class View4: NSView {

@IBOutlet weak var view: View4!

override init(frame frameRect: NSRect) {

    super.init(frame: frameRect)

    Bundle.main.loadNibNamed("View4", owner: self, topLevelObjects: nil)

    self.frame = self.bounds

    self.wantsLayer = true
    self.translatesAutoresizingMaskIntoConstraints = false
    self.layer?.backgroundColor = NSColor.purple.cgColor
    self.roundedCorners(on: self)
    // add xib to custom NSView subclass
    self.addSubview(self.view)

}

required init?(coder: NSCoder) {
    super.init(coder: coder)
}

override func draw(_ dirtyRect: NSRect) {
    super.draw(dirtyRect)

    // Drawing code here.
}
}

The corresponding ViewController:

class View4Controller: NSViewController {

override func loadView() {

    print("View4Controller.loadView")
    self.view = NSView()
    }

override func viewDidLoad() {
    super.viewDidLoad()
     // Do view setup here.

    print("View4Controller.viewDidLoad")
    self.view = View4()
}
}

Solution

  • The idea of an outlet is to have a reference to an object that is outside of your code created. The concept is great for prototyping, but tends to become hard to manage as a project grow.

    If you class is the class, then it can refer to itself. („self“ in swift or „this“ in c++) You don't need an outlet in this case.

    The outlet is normally used by controller that need to maintain the view. The concept is a alternative to creating and configuring the view manually.