【Swift Mac开发】纯代码创建NSViewController


  对于习惯了纯代码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)
    }
    
}

   运行如下图;