Require help with redrawing NSRect

Below is a custom view class:

class MyView: NSView {
   var xloc = 0.0
   var yloc = 0.0
   var width = 400.0
   var height = 200.0
   var myRect = NSRect(x: 0.0, y: 0.0, width: 400.0, height: 200.0)

   ...

override func draw(_ dirtyRect: NSRect) {
   let myColor = NSColor(red: 1.0, green: 1.0, blue: 1.0, alpha: self.alpha)
   myColor.setFill()
   dirtyRect.fill()

   self.myRect = NSRect(x: self.xloc, y: self.yloc, width: self.width, height: self.height)
   self.setNeedsDisplay(myRect)     
   self.myRect.fill(using: NSCompositingOperation.clear)

}

The view controller has a keyDown handler as follows:

override func viewDidLoad() {
    super.viewDidLoad()
    view.window?.backgroundColor = NSColor.white
    NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
        self.keyDown(with: $0)
        return $0
    }
}

override func keyDown(with event: NSEvent) {
    let theView = self.view as! MyView
    if event.keyCode == 126 {
        NSLog("Increasing Y coordinate")
         theView.yloc = theView.yloc + 10
         self.view.display()
    }
}

Below is the AppDelegate.swift's content:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    let window = NSApplication.shared.windows.first
    window?.isOpaque = false
    window?.backgroundColor = NSColor.clear
    window?.ignoresMouseEvents = true
    window?.toggleFullScreen(self)

    window?.collectionBehavior = NSWindow.CollectionBehavior.fullScreenPrimary
    let screenFrame = NSScreen.main?.frame

    window?.setFrame(screenFrame!, display: true)

    let myView = MyView()
    window?.contentView = myView

}

The rectangular hole is seen on the screen initially

The above handler is called whenever I press the up arrow key. The self.view.display() in turn calls the draw() method on the view. But the NSRect is not drawn in the new position. Request you to please help me with this. The expected result is to move (or rather redraw) the NSRect based on the keyboard up arrow click

Currently incomplete code is at: https://github.com/suchindrac/hide_pane_mac

Replies

Where is the link between contentView and self.view ?

Do you confirm "Increasing Y coordinate" is printed ?