I want to programmatically create a new NSWindow, but I can't find a way to succeed. This simple code doesn't display a new window. What's wrong with it?
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
let win = NSWindow(contentRect: NSMakeRect(100, 100, 600, 200),
styleMask: NSResizableWindowMask,
backing: NSBackingStoreType.Buffered, defer: true)
let controller = NSWindowController(window: win)
controller.showWindow(self)
win.makeKeyAndOrderFront(win)
}
}
Xcode 11 • Swift 5.1
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
let newWindow = NSWindow(contentRect: .init(origin: .zero,
size: .init(width: NSScreen.main!.frame.midX,
height: NSScreen.main!.frame.midY)),
styleMask: [.closable],
backing: .buffered,
defer: false)
func createNewWindow() {
newWindow.title = "New Window"
newWindow.isOpaque = false
newWindow.center()
newWindow.isMovableByWindowBackground = true
newWindow.backgroundColor = NSColor(calibratedHue: 0, saturation: 1.0, brightness: 0, alpha: 0.7)
newWindow.makeKeyAndOrderFront(nil)
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
createNewWindow()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}