bor*_*ero 28 macos cocoa swift
不幸的是,我没有在互联网上找到任何有用的东西 - 我想知道,我实际需要输入什么代码来初始化应用程序而不使用Swift中的storyboard或XIB文件.我知道我必须有一个.swift名为的文件main.但我不知道在那里写什么(就像我需要autoreleasepool或类似的东西?).例如,我将NSMenu如何初始化a 以及如何将其添加NSViewController到活动窗口(iOS类似的.rootViewController没有帮助).谢谢你的帮助 ;)
编辑:我实际上不想@NSApplicationMain在前面使用AppDelegate.我宁愿知道那里到底发生了什么,然后自己做.
Dai*_*jan 26
如果您不想拥有@NSApplicationMain属性,请执行以下操作:
添加以下顶级代码:
import Cocoa
let delegate = AppDelegate() //alloc main app's delegate class
NSApplication.sharedApplication().delegate = delegate //set as app's delegate
// Old versions:
// NSApplicationMain(C_ARGC, C_ARGV)
NSApplicationMain(Process.argc, Process.unsafeArgv);  //start of run loop
其余的应该在你的app委托中.例如:
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
    }
}
小智 17
上面的顶级代码示例不再适用于最新版本的Xcode.而是使用这个:
import Cocoa
let delegate = AppDelegate() //alloc main app's delegate class
NSApplication.shared().delegate = delegate //set as app's delegate
let ret = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
在Swift 4中,它再次略有变化,
主文件必须有
import Cocoa
let delegate = AppDelegate()
NSApplication.shared.delegate = delegate
NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
AppDelegate必须是
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
    var newWindow: NSWindow?
    var controller: ViewController?
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        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)
    }
}
视图控制器是相同的
| 归档时间: | 
 | 
| 查看次数: | 10105 次 | 
| 最近记录: |