如何在Swift中实例化NSViewController?

6

我目前的Swift代码:

         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的类。

这两个错误都发生在代码的第二行。提前感谢您的帮助。

2个回答

8
在 Swift 中,你不需要调用类的 init 方法来实例化它们。只需在类型名称后直接放置参数即可,不需要使用 init 方法:
let controller = ViewController(nibName: "ViewController", bundle: NSBundle.mainBundle())

或者,如果nibName与类名匹配,则无需提供nibName:
let controller = ViewController()

2
你必须将 NSBundle.mainBundle() 作为 bundle 参数传递。文档上说 nil 可以,但如果你试图将 nil 作为 bundle 参数传递时,会出现错误信息。 - juniperi
1
@juniperi,你刚刚省去了我很多时间的挫败感。我试图实例化一个NSViewController并将nil传递给bundle,但是一直收到"Could not find an overload for '__conversion' that accepts the supplied arguments"错误。将NSBundle.mainBundle()传递进去可以解决这个问题。谢谢。 - mike

0
我不得不将视图控制器的初始化设为全局常量,以便在整个应用程序中起作用。经过反复思考后,我发现它在本地是有效的,所以将其设置为全局的(将其放在AppDelegate类之外),可以避免“nil”错误的出现。
//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)

    } 
}

同时,使用全局的viewController常量,nil也可以与bundle一起使用。苹果的文档并没有错误。这是在10.9上的情况。根据文档,nil会加载mainBundle。还有,使用相同类名的ViewController()作为全局变量也可以。我已经测试过这三种方法。 - Goodtime

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接