无需 nib 以编程方式实例化 UIViewController

2024-06-25

我想创建一个UIViewController以编程方式进行,无需使用笔尖或故事板。

我认为实施该计划就足够了UIViewController as:

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 文件,则此方法将创建一个普通的 UIView 对象。

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instp/UIViewController/view 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无需 nib 以编程方式实例化 UIViewController 的相关文章

随机推荐