此系列笔记为阅读书籍 Cocoa Programming for OS X(5th Edition) 的笔记
有兴趣的朋友推荐阅读原书, 以获得更完整的知识点.
新建项目


在图二中,如果要使用文档, 把Create Document-Based Application 选项勾选上.
新建MainWindowController, 并且创建Xib


设定窗口名称

删除MainMenu中默认的Window

在AppDelegate中绑定之前创建的MainWindowController
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
// @IBOutlet weak var window: NSWindow!
//注册一个全局变量
var mainWC : MainWindowController?
func applicationDidFinishLaunching(aNotification: NSNotification) {
//通过Nib文件实例化一个 WindowController
let _mainWC = MainWindowController(windowNibName: "MainWindowController")
//显示窗口
_mainWC.showWindow(self)
//绑定变量
self.mainWC = _mainWC
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
运行程序, MyWindow被创建出来了

一种更科学的绑定方法
- 在AppDelegate.swift中并不需要设置"windowNibName", 直接使用默认的构造方法
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
// @IBOutlet weak var window: NSWindow!
//注册一个全局变量
var mainWC : MainWindowController?
func applicationDidFinishLaunching(aNotification: NSNotification) {
let _mainWC = MainWindowController()
_mainWC.showWindow(self)
self.mainWC = _mainWC
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
2.在MainWindowController.swift中重写windowNibName构造方法, 设置默认的NibName
override var windowNibName: String? {
return "MainWindowController"
}
网友评论