Search code examples
xcodexcode8swift-playground

Xcode 8 Playground doesn't display NSView


Xcode doesn't display NSView in the playground. But it's displaying UIView without any problem. Is it a bug?

Code:

let view = NSView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.layer?.backgroundColor = NSColor.white.cgColor
PlaygroundPage.current.liveView = view

Also the Xcode Playground is very slow. Is there any way to speed up the playground?


Solution

  • UIView and NSView both are different in their workings. The code you posted is enough for UIView but not for NSView.

    According to Apple Documentation for NSView:

    An NSView object provides the infrastructure for drawing, printing, and handling events in an app. You typically don’t use NSView objects directly. Instead, you use objects whose classes descend from NSView or you subclass NSView yourself and override its methods to implement the behavior you need.

    and

    draw(_:) draws the NSView object. (All subclasses must implement this method, but it’s rarely invoked explicitly.)

    So, you must inherit NSView and implement draw(_:)

    Here is the code:

    import Cocoa
    import PlaygroundSupport
    
    
    class view: NSView
    {
        override init(frame: NSRect)
        {
            super.init(frame: frame)
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        override func draw(_ dirtyRect: NSRect)
        {
            NSColor.blue.setFill()
            NSRectFill(self.bounds)
        }
    }
    
    var v = view(frame: NSRect(x: 0, y: 0, width: 200, height: 200))
    
    PlaygroundPage.current.liveView = v
    

    Output:

    enter image description here


    It is better to use iOS than macOS in Playground because it is easy and also you can find a ton of tutorials or answers.