我目前正在使用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
的子视图时,我收到以下错误,并且视图没有' t load。
2015-12-06 17:34:18.204 Test[9682:1871784] -[NSNib
_initWithNibNamed:bundle:options:] could not load the nibName:
Test.MyViewController in bundle (null).
我不确定自己做错了什么 - 任何帮助都会受到赞赏。
答案 0 :(得分:28)
来自NSViewController documentation:
如果为nibNameOrNil传入nil,则nibName将返回nil和 loadView将抛出异常;在这种情况下,你必须调用 setView:在调用view之前,或覆盖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!)
}
}