以无编程方式实例化UIViewController

我想创build一个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) 

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

根据文件:

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

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

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

你看到一个透明视图的原因是UIView对象没有背景色。 为了validation这一点,你可以在导航堆栈上按下视图控制器的视图属性的背景颜色。

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

您需要在UIViewControllerloadView方法中设置视图,并将您的根视图分配给view属性。

有关更多详细信息,请参阅https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/loadView

你可以做一些像,

  let vc = UIViewController() let view1 = UIView() view1.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) view1.backgroundColor = UIColor.orangeColor() vc.view = view1 navigationController?.pushViewController(vc, animated: true) 

希望这会帮助:)