2014-06-16 84 views
5

我目前的如何在Swift中实例化NSViewController?

  var appBundle = NSBundle.mainBundle() 
     let controller: ViewController = ViewController.init(nibName:  "ViewController", bundle: nil) 
    self.window.contentView.addSubview(controller.view) 
    controller.view.frame = self.window.contentView.bounds 

斯威夫特代码越来越两个错误。一个是“预期的成员名称或类型名称后的构造函数调用”,另一个是“()不能转换为'ViewController'。作为参考,ViewController是继承自NSViewController的类。

这两个错误都发生。在

回答

7

在SWIFT代码预先感谢第二行,你不叫init的类来实例化它们你离开了初始化,只是把参数的类型名称之后:

let controller = ViewController(nibName: "ViewController", bundle: NSBundle.mainBundle()) 

或者,你应该不需要提供nibName如果它匹配na我的类:

let controller = ViewController() 
+2

你必须通过NSBundle.mainBundle( )作为捆绑。文档说nil是好的,但是如果你试图通过nil作为bundle,你会得到错误信息。 – juniperi

+0

谢谢@ juniperi – drewag

+1

@ juniperi你刚刚救了我多少小时的挫折。我试图实例化一个NSViewController传递nil的包,我一直得到一个“无法找到'__conversion'接受提供的参数”错误的重载。传递NSBundle.mainBundle()修复了这个问题。谢谢 – mike

0

我不得不做出视图控制器一个全局变量的初始化,以便它在整个我的应用程序工作。货架我的大脑之后,我发现它在本地工作,所以使得全球(把它的AppDelegate类之外。对我的作品没有“零”误差)

//global constant 
let viewController = ViewController(nibName: "ViewController", bundle: NSBundle.mainBundle()) 

class AppDelegate: NSObject, NSApplicationDelegate { 
    @IBOutlet var window: NSWindow 

func applicationDidFinishLaunching(aNotification: NSNotification?) { 

    //links and loads the view to the main window 
    self.window.contentView.addSubview(viewController.view) 
    viewController.view.frame = self.window.contentView.bounds 

    //works locally and elsewhere as long as viewController is global! 
    viewController.statusField.stringValue = "TESTING" 
    println(viewController.statusField) 

    } 
} 
+0

也捆绑:无效也与viewController常量是全球性的。 Apple的文档没有错误。无论如何,这是10.9。根据文档,nil加载mainBundle。并让controller = ViewController()也作为具有相同类名的全局使用。我测试了所有三个。 – Goodtime