I want to create a UIViewController
programmatically without the use of a nib or a storyboard.
I thought it would be enough to implement the UIViewController
as:
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Add some setup code here, without it it should just be blank
}
}
instantiate it with let vc = TestViewController(nibName: nil, bundle: nil)
or just TestViewController()
and then just push it:
navigationController?.pushViewController(vc, animated: true)
But it shows the navigationController
(upper bar) with a transparent View (the UIWindow
behind is being shown, I have a multi-window setup)
According to the docs:
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
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.
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)
You'll need to setup your views in the loadView
method of UIViewController
and assign your root view to the view
property.
See https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/loadView for additional details.
You can do something like,
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)
hope this will help :)