以编程方式实例化UIViewController而不使用nib

时间:2016-05-30 13:03:58

标签: ios swift uiviewcontroller uinavigationcontroller

我想在不使用笔尖或故事板的情况下以编程方式创建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,我有一个多窗口设置)

3 个答案:

答案 0 :(得分:8)

根据文件:

  

如果视图控制器没有关联的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)

答案 1 :(得分:1)

您需要使用loadView UIViewController方法设置观看次数,并将根视图分配给view属性。

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

答案 2 :(得分:1)

你可以做点什么,

 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)

希望这会有所帮助:)