【发布时间】:2021-01-05 14:12:51
【问题描述】:
在使用 macOS 的 Swift 中:
通过在 AppDelegate 中删除 @NSApplicationMain(并创建 NSWindowController 的子类),我以编程方式创建主窗口,而不使用情节提要等:
//@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)
}
}
windowController 附加了一个 toolbar、statusBar 和 menuBar: (仅从 NIB 加载 menuBar。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 { $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
}
}
}
}
另外,我需要添加一个 main.swift 文件: (感谢提醒我,apodidae)
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。
但是如何使用自定义 size 和 style 打开一个新窗口(通过新类中的某个方法 - 以编程方式)?
请提供代码示例。
【问题讨论】:
-
请贴出你试过的代码,和
configMainWindow差不多。注意:菜单栏属于应用程序,而不是窗口。最好让NSApplication或AppDelegate创建菜单栏。
标签: swift macos cocoa window programmatically-created