问题描述
不幸的是,我在 Internet 上没有找到任何有用的东西 - 我想知道,在不使用 Swift 中的情节提要或 XIB 文件的情况下,我实际上必须键入哪些代码来初始化应用程序.我知道我必须有一个名为 main
的 .swift
文件.但我不知道在那里写什么(比如我需要 autoreleasepool 或类似的东西吗?).例如,我将如何初始化 NSMenu
以及如何将 NSViewController
添加到活动窗口(iOS 类似的 .rootViewController
没有)帮助).感谢您的帮助;)
Unfortunately, I haven't found anything useful on the Internet - I wanted to know, what code I actually have to type for initializing an application without using storyboard or XIB files in Swift. I know I have to have a .swift
file called main
. But I don't know what to write in there (like do I need autoreleasepool or something like that?). For example, what would I do for initializing an NSMenu
and how would I add a NSViewController
to the active window (iOS's similar .rootViewController
doesn't help). Thanks for any help ;)
我实际上不想在 AppDelegate
前面使用 @NSApplicationMain
.我宁愿知道那里到底发生了什么,然后自己做.
I actually don't want to use @NSApplicationMain
in front of the AppDelegate
. I'd rather know what exactly happens there and then do it myself.
推荐答案
如果您不想拥有 @NSApplicationMain 属性,请执行以下操作:
if you don't want to have the @NSApplicationMain attribute, do:
有一个文件 main.swift
have a file 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);
其余的应该在您的应用程序委托中.例如:
the rest should be inside your app delegate. e.g.:
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)
}
}
那么你就有了一个视图控制器
then you have a 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
}
}
这篇关于没有故事板或使用 Swift 的 xib 文件的 OSX 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!