以编程方式实例化UIViewController而不使用nib

Dan*_*iel 6 uiviewcontroller uinavigationcontroller ios swift

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

我认为实现UIViewControlleras 是足够的:

class TestViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //Add some setup code here, without it it should just be blank
    }
}
Run Code Online (Sandbox Code Playgroud)

let vc = TestViewController(nibName: nil, bundle: nil)或只是实例化它 TestViewController()

然后推它:

navigationController?.pushViewController(vc, animated: true)
Run Code Online (Sandbox Code Playgroud)

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

Ahm*_*ale 9

根据文件:

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

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

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

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

let viewController = TestViewController()
viewController.view.backgroundColor = .blueColor()
navigationController?.pushViewController(viewController, animated: true)
Run Code Online (Sandbox Code Playgroud)