ios - 在没有 nib 的情况下以编程方式实例化 UIViewController

标签 ios swift uiviewcontroller uinavigationcontroller

我想在不使用 Nib 或 Storyboard的情况下以编程方式创建一个 UIViewController

我认为将 UIViewController 实现为:

class TestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //Add some setup code here, without it it should just be blank
    }
}

let vc = TestViewController(nibName: nil, bundle: nil) 或只是 TestViewController()

实例化它

然后只需插入它:

navigationController?.pushViewController(vc, animated: true)

但是它显示了带有透明 View 的navigationController(上栏)(显示了后面的UIWindow,我有一个多窗口设置)

最佳答案

根据文档:

If the view controller does not have an associated nib file, this method creates a plain UIView object instead.

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instp/UIViewController/view

如果您在实例化 View Controller 时没有提供 nib 文件,UIViewController 会调用它的 loadView() 方法创建一个普通的 UIView 对象并将其分配给它的 View 属性。

您看到透明 View 的原因是因为 UIView 对象没有背景颜色。要验证这一点,您可以在将 View Controller 的 View 属性推送到导航堆栈之前设置它的背景颜色。

let viewController = TestViewController()
viewController.view.backgroundColor = .blueColor()
navigationController?.pushViewController(viewController, animated: true)

关于ios - 在没有 nib 的情况下以编程方式实例化 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37526411/

相关文章:

ios - 如何使用vDSP_conv来模拟MATLAB的xcorr函数?

ios - 使用 UIBezierPath 设置某些角的半径并向自定义 UIButton 添加阴影

ios - Firebase for iOS 内部框架

swift - 无法在 subview 中设置 var

ios - 检查当前的 rootViewController 是什么?

ios - 添加一个 uilabel 没有改变的 uiviewcontroller

ios - 如何在 Windows 上为 IOS 构建 NativeScript 项目?

ios - NSCameraUsageDescription 在 Xcode 9 中不起作用

ios - 将 Int 传递给枚举并返回一个 String

ios - DataFormatterStyle 没有成员 .mediumStyle