對於習慣了純代碼iOS開發的人來說,剛接觸Mac端開發時,是非常不友好的,網上所有的教程都是通過Xib或StoryBoard的方式創建NSViewController,而且蘋果文檔也是鼓勵用Xib的開發進行Mac 開發,但對於純代碼開發也給了補救方式,現在給大家分享一種可以直接代碼創建的方式。
Apple Document:
If you pass in a nil for nibNameOrNil then nibName will return nil and loadView will throw an exception; in this case you must invoke setView: before view is invoked, or override loadView.
翻譯如下:
如果為nbNameOrNil傳遞nil,則nibName將返回nil,並且loadView會引發異常;在這種情況下,您必須在調用視圖之前調用setView:,或重寫loadView。
如果不補救,對於通過JFProgrammaticallyViewController()創建的控制器,會報如下錯誤:
-[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: CodeCreateUiDemo.JFProgrammaticallyViewController in bundle (null).
廢話少說,上代碼:
import Cocoa import SnapKit class ViewController: NSViewController { var button : NSButton! override func viewDidLoad() { super.viewDidLoad() button = NSButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) button.wantsLayer = true button.layer?.backgroundColor = NSColor.red.cgColor button.title = "click" button.target = self button.action = #selector(clickAction(sender:)) self.view.addSubview(button) } @objc func clickAction(sender:NSButton) { let programmaticallyVC = JFProgrammaticallyViewController() self.presentAsModalWindow(programmaticallyVC) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } } //純代碼創建的ViewController import Cocoa class JFProgrammaticallyViewController: NSViewController { var mView : NSView! //這一端是重重之中,對於無法通過Nib加載view,就要通過loadView()方法來進行補救, override func loadView() { self.view = NSView(frame: CGRect(x: 0, y: 0, width: 400, height: 300)) } override func viewDidLoad() { super.viewDidLoad() mView = NSView(frame: NSRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)) mView.wantsLayer = true mView.layer?.backgroundColor = NSColor.red.cgColor self.view.addSubview(mView) } }
運行如下圖;