我目前正在使用Swift 2编写OS X应用程序.我想在没有XIB或Storyboard的情况下构建UI.我遇到的问题是初始化我可以将我的视图放入的自定义ViewController.
这是我的AppDelegate:
@NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var viewController: MyViewController? func applicationDidFinishLaunching(aNotification: NSNotification) { viewController = MyViewController() self.window.contentView!.addSubview(viewController!.view) } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
和MyViewController:
class MyViewController: NSViewController { var textField: NSTextField? override func viewDidLoad() { super.viewDidLoad() textField = NSTextField(frame: NSRect(x: 10, y: 10, width: 100, height: 100)) textField!.bezeled = false textField!.drawsBackground = false textField!.editable = false textField!.selectable = false textField!.stringValue = "TEST" self.view.addSubview(textField!) } }
问题是,当我将viewController
视图添加为窗口的子视图时contentView
,我收到以下错误并且视图未加载.
2015-12-06 17:34:18.204 Test[9682:1871784] -[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: Test.MyViewController in bundle (null).
我不确定我做错了什么 - 任何帮助都会受到赞赏.
从NSViewController文档:
如果为nibNameOrNil传入nil,则nibName将返回nil,loadView将抛出异常; 在这种情况下,您必须在调用view之前调用setView:或覆盖loadView.
初始化为MyViewController()
用途nil
的nibName.
两个可能的修复:
func applicationDidFinishLaunching(aNotification: NSNotification) { viewController = MyViewController() viewController!.view = NSView() // added this line; edit to set any view of your choice self.window.contentView!.addSubview(viewController!.view) }
交替,
import Cocoa class MyViewController: NSViewController { var textField: NSTextField? override func loadView() { self.view = NSView() // any view of your choice } override func viewDidLoad() { super.viewDidLoad() textField = NSTextField(frame: NSRect(x: 10, y: 10, width: 100, height: 100)) textField!.bezeled = false textField!.drawsBackground = false textField!.editable = false textField!.selectable = false textField!.stringValue = "TEST" self.view.addSubview(textField!) } }