MacOS开发笔记(一): HelloWorld

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

新建项目

选择CocoaApplication
和iOS开发一样, 设定项目名称

在图二中,如果要使用文档, 把Create Document-Based Application 选项勾选上.

新建MainWindowController, 并且创建Xib

Cmd+N调出新建面板, 选择Cocoa Class
勾选 create XIB file

设定窗口名称

选择MainWindowController.xib, 把Title设置成MyWindow

删除MainMenu中默认的Window

选择Window, 点Delete删除

在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被创建出来了

HelloWorld

一种更科学的绑定方法

  1. 在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"
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容