我想在不使用 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.
如果您在实例化 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/