xcode 如何在 Swift 中实例化 NSViewController?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24236348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:06:06  来源:igfitidea点击:

How to instantiate NSViewController in Swift?

iosobjective-cxcodeswiftnsviewcontroller

提问by Team6Labs

My current Swift code of

我目前的 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

is getting two errors. One is "Expected member name or constructor call after type name" and the other is "() is not convertible to 'ViewController'. For reference, ViewController is a class that inherits from NSViewController.

有两个错误。一个是“Expected member name or constructor call after type name”,另一个是“() is not convertible to 'ViewController'。供参考,ViewController是一个继承自NSViewController的类。

Both of the errors are occurring on the second line of code. Thanks in advance.

这两个错误都发生在第二行代码上。提前致谢。

回答by drewag

In swift you don't call initon classes to instantiate them. You leave out the init and just put the arguments right after the type name:

在 swift 中,您不会调用init类来实例化它们。您省略了 init 并将参数放在类型名称之后:

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

or, you shouldn't need to provide the nibNameif it matches the name of the class:

或者,nibName如果它与类的名称匹配,则不需要提供:

let controller = ViewController()

回答by Goodtime

I had to make the initialization of the view controller a global constant in order for it to work throughout my app. After racking my brain, I found that it was working locally, so making it global (putting it outside the AppDelegate class. works for me without the "nil" error)

我必须将视图控制器的初始化设置为全局常量,以便它在我的应用程序中正常工作。绞尽脑汁后,我发现它在本地工作,因此将其设为全局(将其放在 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)

    } 
}