Here is a programmatic approach which may be run in Terminal. Note that window.acceptsMouseMovedEvents is set to true.
//May be run in Terminal with:
//swiftc label.swift -framework Cocoa -o label && ./label
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var window : NSWindow!
var here2 = [NSTextField]()
var count: Int = 0
let _wndW : CGFloat = 700
let _wndH : CGFloat = 750
let _labelW : CGFloat = 24
let _labelH : CGFloat = 24
@objc func getCoordinates(_ sender:AnyObject ) {
NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown]) {
var pt: NSPoint? { self.window.mouseLocationOutsideOfEventStream }
if let location = pt {
let msPt:NSPoint = self.window.contentView!.convert(location, from: nil)
print("x = \(msPt.x) : y = \(msPt.y)")
if msPt.x < (self._wndW - self._labelW) && msPt.y < (self._wndH - self._labelH ) {
self.here2.append(NSTextField.init())
self.here2[self.count].frame = NSMakeRect(msPt.x, msPt.y, self._labelW, self._labelH)
print(self.here2[self.count].frame)
self.window.contentView!.addSubview (self.here2[self.count])
self.here2[self.count].backgroundColor = NSColor.white
self.here2[self.count].isSelectable = false
self.here2[self.count].stringValue = String(self.count)
print("count is: " + String(self.here2.count))
self.count+=1
}
}
return $0
}
}
func buildMenu() {
let mainMenu = NSMenu()
NSApp.mainMenu = mainMenu
// **** App menu **** //
let appMenuItem = NSMenuItem()
mainMenu.addItem(appMenuItem)
let appMenu = NSMenu()
appMenuItem.submenu = appMenu
appMenu.addItem(withTitle: "Quit", action:#selector(NSApplication.terminate), keyEquivalent: "q")
}
func buildWnd() {
window = NSWindow(contentRect:NSMakeRect(0,0,_wndW,_wndH),styleMask:[.titled, .closable, .miniaturizable, .resizable], backing:.buffered, defer:false)
window.center()
window.title = "Swift Test Window"
window.makeKeyAndOrderFront(window)
window.acceptsMouseMovedEvents = true
// **** Button **** //
let myBtn = NSButton (frame:NSMakeRect( _wndW - 180, 15, 135, 24 ))
myBtn.bezelStyle = .rounded
myBtn.autoresizingMask = [.maxXMargin,.minYMargin]
myBtn.title = "Start Label Maker"
myBtn.action = #selector(self.getCoordinates(_:))
window.contentView!.addSubview (myBtn)
// **** Quit btn **** //
let quitBtn = NSButton (frame:NSMakeRect( _wndW - 50, 10, 40, 40 ))
quitBtn.bezelStyle = .circular
quitBtn.autoresizingMask = [.minXMargin,.maxYMargin]
quitBtn.title = "Q"
quitBtn.action = #selector(NSApplication.terminate)
window.contentView!.addSubview(quitBtn)
}
func applicationDidFinishLaunching(_ notification: Notification) {
buildMenu()
buildWnd()
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
let appDelegate = AppDelegate()
// **** main.swift **** //
let app = NSApplication.shared
app.delegate = appDelegate
app.setActivationPolicy(.regular)
app.activate(ignoringOtherApps:true)
app.run()