Search code examples
swiftnsviewappkit

How to set NSView Instance Properties


In the NSView class documentation, there is a symbol canDraw that indicates whether drawing commands will produce any results.

The declaration is var canDraw: Bool { get } - so anytime you try something such as

@IBOutlet weak var myView: NSView!

then myView.canDraw = true, you get a build-time error stating "Cannot assign to property: 'canDraw' is a get-only property". However, if I want to draw NSRect onto my view, how can I change this property?


Solution

  • You can't change canDraw because it is read-only. It is read-only because it reports a matter of fact, over which you have no control, namely, whether this is a view you can draw into at this moment.

    To draw into a view — that is, to implement an NSView that takes charge of drawing itself — subclass NSView and implement draw. Example:

    enter image description here

    The code shown in that screen shot is basically the only code in the application. The view in the window is a MyView, and MyView implements draw.