百度无数,谷歌无数,都特么只有xib和storyboard的文章,但是个人就是喜欢纯代码,所以试验了无数次总结了下面的方法.
第一步创建工程,然后在工程里面删除 storyboard.
然后在AppDelegate 里面删除@NSApplicationMain这一句.
在info.plist里面删除NSMainStoryboardFile这一行.
这时候App就不会自动查找storyboard了.
第二步创建一个main.swift文件,代码如下:
import Cocoa
let delegate = AppDelegate()
NSApplication.shared().delegate = delegate
NSApplication.shared().run()
第三步在AppDelegate里面加上如下代码:
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var newWindow: NSWindow?
var controller: ViewController?
func applicationDidFinishLaunching(_ aNotification: Notification) {
newWindow = NSWindow(contentRect: NSMakeRect(200, 200, 300, 300), styleMask: .fullScreen, backing: .buffered, defer: false)
controller = ViewController()
let content = newWindow?.contentView!
let view = controller?.view
content?.addSubview(view!)
newWindow?.makeKeyAndOrderFront(nil)
}
}
第四步在ViewController里面加上如下代码:
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
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
}
}
编译运行一下就会出现一个最原始的窗口,然后自己在里面加各种控件就好了