在 Swift 中更改 RootViewController 类型

Changing RootViewController type in Swift

好的,我一直在学习教程,我已经完成了,一切正常。然而,加载的初始视图是一个 UITableViewController,我想要一个 UIViewController。

这是代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    
    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()
    
    window?.rootViewController = UINavigationController(rootViewController: ViewController())
    
    return true
}

我试过编辑这一行:

UINavigationController(rootViewController: ViewController())

至:

window?.rootViewController = UIViewController(rootViewController: ViewController())

但是我得到了这个错误:

Incorrect argument label in call (have 'rootViewController:', expected 'coder:')

然后它要求我 'Fix-it' 所以我做了,这将行更改为:

window?.rootViewController = UIViewController(coder: ViewController())

但是这现在抛出错误:

Cannot convert value of type 'ViewController' to expected argument type 'NSCoder'

我也试过:

window?.rootViewController = ViewController()

但是,模拟器变黑了。

澄清问题:

如何让我的应用中加载的第一个视图成为 UIViewController 类型?

你应该子类化 UIViewController 并制作你自己的版本来检查它是否有效,但你最初所做的是好的

let myViewController = SomeViewController()
let navigationController = UINavigationController(rootViewController: myViewController)
window?.rootViewController = navigationController

然后在SomeViewControllerviewDidLoad设置view.backgroundColor = .red

如果要删除导航栏可以将其设置为隐藏

navigationController.navigationBarHidden = true

或者...

let myViewController = SomeViewController()
window?.rootViewController = myViewController

也会工作...虽然您应该希望保持导航控制器的一般性..它通常会使将来呈现视图控制器更容易...

您的模拟器变黑的原因是因为它可以正常工作...您显示的是一个空 UIViewController...您必须创建自己的 UIViewController 子类并向其中添加内容。

您的视图控制器子类应该如下所示

//
//  SomeViewController.swift
//  SomeProject
//
//  Created by Magoo on 17/10/2016.
//  Copyright © 2016 Magoo. All rights reserved.
//

import UIKit

class SomeViewController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()
        view.backgroundColor = .red

        let label = UILabel(frame:view.bounds)
        label.textColor = UIColor.whiteColor()
        label.text = "Hello world"

        view.addSubview(label)
    }
}

结果应该是红屏,中间写着'Hello world'。