NSView draw() being called twice

Viewed 102

I'm new to swift and Cocoa dev my problem is:-

NSView's draw() function is being called twice. the results and code are below :-

results

[3/3] Linking MyCanvasApp
Hello, World
You got nothing.
You got nothing.
^C

as you can see "You got nothing" is being printed twice

PS everything is handwritten I'm not using Xcode at all

main.swift

import Cocoa 

var app = NSApplication.shared
app.setActivationPolicy(.regular)
let delegate = AppDelegate()
app.delegate = delegate
app.activate(ignoringOtherApps: true)
app.run()

AppDelegate.swift

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        print("Hello, World")
        let frame = NSRect.init(x: 100.0, y: 100.0, width: 300.0, height: 300.0)
        let win = NSWindow.init(contentRect: frame, styleMask: [.closable, .titled], backing: .buffered, defer: false)
        win.title = "My Canvas App"
        win.makeKeyAndOrderFront(nil)
        let frame2 = NSRectToCGRect(NSRect.init(x: 0, y: 0, width: 300.0, height: 300.0))
        let canvas = CanvasView.init(frame: frame2)
        win.contentView!.addSubview(canvas)
    }
}

does NSView.init (CanvasView.init) calls it or something? ^^

CanvasView.swift

import Cocoa

class CanvasView: NSView {
    var Mode: CanvasMode = CanvasMode.Rectangle
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

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

    override func draw(_ rect: CGRect) {
        // super.draw(rect)
        // var context: CGContext = NSGraphicsContext.current!.CGContext
        self.wantsLayer = true
        self.layer?.backgroundColor = NSColor.yellow.cgColor
        switch Mode {
            case .Line:
                print("You got Line.")
            default:
                print("You got nothing.")
        }
    }

    override func mouseDown(with theEvent: NSEvent) {
        print("left mouse")
    }

    override func rightMouseDown(with theEvent: NSEvent) {
        print("right mouse")
    }

    override func mouseDragged(with theEvent: NSEvent) {
        print("mouseDragged")
    }
}

CanvasMode.swift

import Cocoa

enum CanvasMode {
    case Line
    case Rectangle
    case Triangle
}
0 Answers
Related