此系列筆記為閱讀書籍 Cocoa Programming for OS X(5th Edition) 的筆記
有興趣的朋友推薦閱讀原書, 以獲得更完整的知識(shí)點(diǎn).
新建項(xiàng)目
選擇CocoaApplication
和iOS開(kāi)發(fā)一樣, 設(shè)定項(xiàng)目名稱
在圖二中,如果要使用文檔, 把Create Document-Based Application 選項(xiàng)勾選上.
新建MainWindowController, 并且創(chuàng)建Xib
Cmd+N調(diào)出新建面板, 選擇Cocoa Class
勾選 create XIB file
設(shè)定窗口名稱
選擇MainWindowController.xib, 把Title設(shè)置成MyWindow
刪除MainMenu中默認(rèn)的Window
選擇Window, 點(diǎn)Delete刪除
在AppDelegate中綁定之前創(chuàng)建的MainWindowController
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
// @IBOutlet weak var window: NSWindow!
//注冊(cè)一個(gè)全局變量
var mainWC : MainWindowController?
func applicationDidFinishLaunching(aNotification: NSNotification) {
//通過(guò)Nib文件實(shí)例化一個(gè) WindowController
let _mainWC = MainWindowController(windowNibName: "MainWindowController")
//顯示窗口
_mainWC.showWindow(self)
//綁定變量
self.mainWC = _mainWC
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
運(yùn)行程序, MyWindow被創(chuàng)建出來(lái)了
HelloWorld
一種更科學(xué)的綁定方法
- 在AppDelegate.swift中并不需要設(shè)置"windowNibName", 直接使用默認(rèn)的構(gòu)造方法
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
// @IBOutlet weak var window: NSWindow!
//注冊(cè)一個(gè)全局變量
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構(gòu)造方法, 設(shè)置默認(rèn)的NibName
override var windowNibName: String? {
return "MainWindowController"
}