无法在Swift中编程创建UIViewController [英] Unable to programatically create a UIViewController in Swift

查看:213
本文介绍了无法在Swift中编程创建UIViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在 Swift 中创建 UIViewController 的实例时,所有继承的初始化器都不可用,甚至虽然我没有在视图控制器(或任何其他,FWIW)中定义任何指定的inits。

When I try to create an instance of a UIViewController in Swift, all the inherited initialisers are unavailable, even though I didn't define any designated inits in the view controller (or anything else, FWIW).

此外,如果我尝试显示它,控制器,它从不显示:

Also, if I try to display it by making it the root view controller, it never gets displayed:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.makeKeyAndVisible()
        window?.backgroundColor = UIColor.greenColor()



        let vc = ImageViewController()
        window?.rootViewController = vc

        return true
    }

视图控制器的代码只是Xcode的模板:

The code for the view controller is just Xcode's template:

import UIKit

class ImageViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

知道发生了什么????

Anybody knows what's going on????

推荐答案

正如你所指出的:只要nib名称匹配类名在objective-C中,即使在初始化视图控制器时没有指定nib名称,视图控制器仍然会查看其名称与视图控制器类的名称匹配的nib文件

As you've pointed out: As long as the nib name matches the class name in objective-C, even if you don't specify a nib name when initializing the view controller, the view controller will still look for the nib file whose name matches the name of the view controller class.

但是由于某种原因(也许是一个错误),在Swift中不是这样。

But for some reason (perhaps it's a bug), this is not the case in Swift.

而不是写:

let vc = ImageViewController()

您必须在初始化视图控制器时显式指定一个接口:

You have to explicitly specify an interface when initializing the view controller:

let vc = ImageViewController(nibName: "nibName", bundle: nil)

这篇关于无法在Swift中编程创建UIViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆