在没有笔尖的情况下以编程方式实例化

在没有笔尖的情况下以编程方式实例化

本文介绍了在没有笔尖的情况下以编程方式实例化 UIViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用笔尖或故事板的情况下以编程方式创建一个 UIViewController.

I want to create a UIViewController programmatically without the use of a nib or a storyboard.

我认为将 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)

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

But it shows the navigationController (upper bar) with a transparent View (the UIWindow behind is being shown, I have a multi-window setup)

推荐答案

根据文档:

如果视图控制器没有关联的 nib 文件,这个方法会创建一个普通的 UIView 对象.

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

如果在实例化视图控制器时没有提供 nib 文件,UIViewController 会调用它的 loadView() 方法,该方法创建一个普通的 UIView 对象并将其分配给它的视图属性.

If you do not provide a nib file when instantiating the view controller, UIViewController calls it's loadView() method which creates a plain UIView object and assigns it to its view property.

之所以看到透明视图,是因为 UIView 对象没有背景色.为了验证这一点,您可以在将视图控制器的视图属性推送到导航堆栈之前设置它的背景颜色.

The reason why you are seeing a transparent view is because the UIView object has no background color. To verify this, you can set the background color of the view controller's view property right before you push it on your navigation stack.

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

这篇关于在没有笔尖的情况下以编程方式实例化 UIViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:05