Swift 在 macOS 中以编程方式打开新的 window

Swift open new window programmatically in macOS

在 Swift 中使用 macOS: 通过在 AppDelegate 中删除 @NSApplicationMain(并创建 NSWindowController 的子class),我创建了主 window 以编程方式,不使用故事板等:

//@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)
    }
}

window控制器附加了一个工具栏状态栏菜单栏: (只有 menuBar 从 NIB 加载。class MainMenuAction 处理菜单选择。)

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 { [=13=] 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
            }
        }
    }
}

此外,我需要添加一个 main.swift 文件: (感谢提醒,猿猴)

let delegate = AppDelegate()
NSApplication.shared.delegate = delegate
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)

我试过了:

    let vc = NSViewController()
    let win = configWindow(vc, windowWidth: 420, windowHeight: 673)
    let wc = NSWindowController(window: win)
    wc.window?.present
    vc.view.window?.contentViewController = vc

我从 AppDelegate 复制了方法 configMainWindow,以创建允许我指定大小和 vc.

的 configWindow

但是我如何打开一个新的 window(从新 class 中的某种方法 - 以编程方式)和自定义 尺码样式?

请提供代码示例。

以下演示创建了第二个 window,由自定义 class 中的方法调用。通过添加'swift.main'文件并用以下代码替换AppDelegate,可以在Xcode中运行:

import Cocoa

class Abc : NSObject {
var panel: NSPanel!

func buildWnd2() {
 let _panelW : CGFloat = 200
 let _panelH : CGFloat = 200

 panel = NSPanel(contentRect:NSMakeRect(9300, 1300, _panelW, _panelH), styleMask:[.titled, .closable, .utilityWindow],
  backing:.buffered, defer: false)         
 panel.isFloatingPanel = true
 panel.title = "NSPanel"
 panel.orderFront(nil)
}
}

let abc = Abc()

class AppDelegate: NSObject, NSApplicationDelegate {
var window:NSWindow!

@objc func myBtnAction(_ sender:AnyObject ) {
 abc.buildWnd2()
}

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() {
    
let _wndW : CGFloat = 400
let _wndH : CGFloat = 300

 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)

// **** Button **** //
let myBtn = NSButton (frame:NSMakeRect( 100, 100, 175, 30 ))
 myBtn.bezelStyle = .rounded
 myBtn.autoresizingMask = [.maxXMargin,.minYMargin]
 myBtn.title = "Build Second Window"
 myBtn.action = #selector(self.myBtnAction(_:))
 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()