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

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

问题描述

当我尝试在 Swift 中创建 UIViewController 的实例时,所有继承的初始化器都不可用,即使我没有在视图中定义任何指定的初始化控制器(或其他任何东西,FWIW).

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????

推荐答案

正如您所指出的:只要笔尖名称与 Objective-C 中的类名称匹配,即使您在以下情况下不指定笔尖名称初始化视图控制器,视图控制器仍然会 查找名称与视图控制器类名称匹配的 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天全站免登陆