无需使用nib文件编程实例化UIViewController

10

我希望能够通过编程创建一个UIViewController,而不使用nib或storyboard。

我认为只需将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)。

3个回答

17

根据文档:

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

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

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

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

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

看起来我使用了 viewDidLoad 而不是 loadView。这就是我的问题所在。 - Daniel
没错。如果您需要为视图控制器提供自定义的UIView实现,则可以重写loadView方法。 - Ahmed Onawale

2

每个UIViewController都应该有一个顶层视图,它拥有包含所有其他视图的视图。对此视图的引用存储在UIViewController的view属性中。有关此属性的更多详细信息,请参阅此处:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instp/UIViewController/view - Casey Fleser

0
你可以这样做:
 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)

希望这能有所帮助 :)

这没有任何区别。行为相同。 - Daniel
将视图的背景颜色设置为使您了解它正在工作。 - Ketan Parmar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接