In Swift using macOS:
By removing @NSApplicationMain
(and making a subclass of NSWindowController) in AppDelegate I create the main window programmatically, without using storyboards, etc.:
//@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
var viewController: NSViewController!
var windowController: NSWindowController!
func configMainWindow(_ viewController: NSViewController) {
window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 800, height: 600),
styleMask: [NSWindow.StyleMask.closable, NSWindow.StyleMask.titled, NSWindow.StyleMask.resizable, NSWindow.StyleMask.miniaturizable],
backing: NSWindow.BackingStoreType.buffered,
defer: false)
window.title = "My App"
window.setFrameAutosaveName("My App")
window.center()
window.isOpaque = false
window.isMovableByWindowBackground = true
window.backgroundColor = NSColor.white
window.makeKeyAndOrderFront(nil)
window.contentViewController = viewController
windowController = WindowController(window: window)
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
viewController = ViewController()
configMainWindow(viewController)
}
}
The windowController attaches a toolbar, statusBar and menuBar: (Only the menuBar is loaded from a NIB. A class MainMenuAction handles the menu choices.)
class WindowController: NSWindowController, NSWindowDelegate {
var toolbarController = ToolbarController()
var statusBarController = StatusBarController()
var mainMenuAction: MainMenuAction?
override init(window: NSWindow?) {
super.init(window: window)
window?.toolbar = toolbarController.toolbar
window?.delegate = self
var topLevelObjects: NSArray? = []
Bundle.main.loadNibNamed("MainMenu", owner: self, topLevelObjects: &topLevelObjects)
NSApplication.shared.mainMenu = topLevelObjects?.filter { $0 is NSMenu }.first as? NSMenu
self.mainMenuAction = MainMenuAction.shared
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func windowDidLoad() {
if let window = window {
if let view = window.contentView {
view.wantsLayer = true
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
window.backgroundColor = .white
}
}
}
}
Additionally, I needed to add a main.swift file: (thanks for reminding me, apodidae)
let delegate = AppDelegate()
NSApplication.shared.delegate = delegate
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
I tried:
let vc = NSViewController()
let win = configWindow(vc, windowWidth: 420, windowHeight: 673)
let wc = NSWindowController(window: win)
wc.window?.present
vc.view.window?.contentViewController = vc
Where I copied the method configMainWindow from AppDelegate, to create configWindow that allowed me the specify size and the vc.
But how can I open a new window (from some method in a new class - programmatically) with a custom size and style?
Please provide a code example.