Subclassing a NSViewController in a MacOS Playground

I am trying to subclass a NSViewController as a part of my application. I can get equivalent code to work in an iOS playground but something about the way MacOS does things causes things not to work.


I was hoping that this code:


import AppKit
import PlaygroundSupport
class PVC: NSViewController {
    var textField: NSTextField?
   
    override func loadView() {
        print("Loading view")
        self.view = NSView() /
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        print("did load")
        textField = NSTextField(frame: NSRect(x: 10, y: 10, width: 100, height: 100))
        textField!.isBezeled = false
        textField!.drawsBackground = false
        textField!.isEditable = false
        textField!.isSelectable = false
        textField!.stringValue = "TEST"
        self.view.addSubview(textField!)
    }
   
}
let vc = PVC()
PlaygroundPage.current.liveView = vc

Would cause my view controller to be displayed in the live view however it is just blank although no errors are generated. Both print statements are printed.


Why is this not working?

Accepted Reply

With this line of your code:

self.view = NSView()

you are creating the main view of your view controller with an empty initializer of `NSView`.


How `NSView.init()` would work is not well documentend, but you may be creating a zero-sized view.

Please check what happens if you change the line to:

self.view = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: 300))

Replies

With this line of your code:

self.view = NSView()

you are creating the main view of your view controller with an empty initializer of `NSView`.


How `NSView.init()` would work is not well documentend, but you may be creating a zero-sized view.

Please check what happens if you change the line to:

self.view = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: 300))

Yeah that worked brilliantly but I am very confused now.


One of the main beauties of the UIViewController is that it seems to keep the view at the appropriate scale to fill the view controller. NSViewController does not seem to have such a feature. Is there any way to automatically have my view resized to fill the area that it is in? What is the proper way to resize my view controller to allow for a larger view to be added?


Is a NSViewController really not much of a view controller? Perhaps all it can do is hold a view and load a view from stored nibs?

One of the main beauties of the UIViewController is that it seems to keep the view at the appropriate scale to fill the view controller.

Is that so? Anyway, `UIView.init()` is also not well defined and in my iOS apps I have never used the default initializer of `UIView`.


`NSViewController` is not the same as `UIViewController`. You should better not expect it to be the same as `UIViewController` especially for undocumented behaviors.