macos - 没有 Storyboard或使用 Swift 的 xib 文件的 OSX 应用程序

标签 macos cocoa swift

不幸的是,我没有在互联网上找到任何有用的东西——我想知道,在不使用 Storyboard或 Swift 中的 XIB 文件的情况下,我实际上必须键入哪些代码来初始化应用程序。我知道我必须有一个名为 main.swift 文件。但我不知道在那里写什么(比如我需要 autoreleasepool 或类似的东西吗?)。例如,我将如何初始化 NSMenu 以及如何将 NSViewController 添加到事件窗口(iOS 的类似 .rootViewController 没有帮助)。感谢您的帮助;)

编辑: 我实际上不想在 AppDelegate 前面使用 @NSApplicationMain。我宁愿知道那里到底发生了什么,然后自己动手。

最佳答案

如果您不想拥有@NSApplicationMain 属性,请执行以下操作:

  1. 有一个文件 main.swift

  2. 添加以下顶层代码:

     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 - 没有 Storyboard或使用 Swift 的 xib 文件的 OSX 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43857296/

相关文章:

macos - sublime中使用emmet时重新定义ctrl-d

objective-c - 具有校准值的 NSColor 的工作方式与常规颜色不同吗?

swift - 以编程方式快速发送到自定义创建 View 中的前端 UIButton

objective-c - 使用 NSView 实例作为 NSDictionary 键?

ios - {"cod":401, "message":“使用 Moya 时出现 Open Weather API 错误,API key 无效

ios - 在数组中查找自定义对象索引

c++ - OpenCL - GPU 上的多线程

macos - 您没有/Library/Ruby/Gems/2.3.0 目录的写权限。 (mac 用户)

swift - NSTask 输出缓冲区大小问题(运行 SPApplicationsDataType 命令)

cocoa - Cocoa 上的 Qt 或 wxWidgets?