当前位置:  开发笔记 > IOS > 正文

在没有xib文件的情况下初始化NSViewController的子类

如何解决《在没有xib文件的情况下初始化NSViewController的子类》经验,为你挑选了1个好方法。

我目前正在使用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).

我不确定我做错了什么 - 任何帮助都会受到赞赏.



1> truncated..:

从NSViewController文档:

如果为nibNameOrNil传入nil,则nibName将返回nil,loadView将抛出异常; 在这种情况下,您必须在调用view之前调用setView:或覆盖loadView.

初始化为MyViewController()用途nil的nibName.

两个可能的修复:

1.在AppDelegate中设置视图

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)
}

交替,

2.在子类ViewController中覆盖loadView

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!)
    }

}

推荐阅读
mobiledu2402852413
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有