不幸的是,我在互联网上没有找到任何有用的东西 - 我想知道,在不使用 Swift 中的 Storyboard 或 XIB 文件的情况下,我实际上需要键入哪些代码来初始化应用程序。我知道我必须有一个名为 main
的 .swift
文件。但我不知道在那里写什么(比如我需要 autoreleasepool 或类似的东西吗?)。例如,我将如何初始化 NSMenu
以及如何将 NSViewController
添加到事件窗口(iOS 的类似 .rootViewController
则不会)没有帮助)。感谢您的帮助;)
编辑:
我实际上不想在 AppDelegate
前面使用 @NSApplicationMain
。我宁愿知道那里到底发生了什么,然后自己去做。
最佳答案
如果您不想拥有 @NSApplicationMain 属性,请执行以下操作:
有一个文件 main.swift
添加以下顶级代码:
import Cocoa let delegate = AppDelegate() //alloc main app's delegate class NSApplication.shared.delegate = delegate //set as app's delegate NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv) //start of run loop // Old versions: // NSApplicationMain(C_ARGC, C_ARGV) // NSApplicationMain(Process.argc, Process.unsafeArgv);
其余部分应该位于您的应用程序委托(delegate)内。例如:
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var newWindow: NSWindow?
var controller: ViewController?
func applicationDidFinishLaunching(aNotification: NSNotification) {
newWindow = NSWindow(contentRect: NSMakeRect(10, 10, 300, 300), styleMask: .resizable, backing: .buffered, defer: false)
controller = ViewController()
let content = newWindow!.contentView! as NSView
let view = controller!.view
content.addSubview(view)
newWindow!.makeKeyAndOrderFront(nil)
}
}
那么你就有了一个viewController
import Cocoa
class ViewController : NSViewController {
override func loadView() {
let view = NSView(frame: NSMakeRect(0,0,100,100))
view.wantsLayer = true
view.layer?.borderWidth = 2
view.layer?.borderColor = NSColor.red.cgColor
self.view = view
}
}
关于macos - 使用 Swift 的没有 Storyboard 或 xib 文件的 OSX 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46564230/