How to setup view in UIViewController

I've created an almost-empty UIViewController class named MyViewController . In the viewDidLoad I'm setting the title and adding a close-button to the navigationItem.leftBarButtonItem.

I'm presenting my MyViewController like this:

MyViewController *myViewController = [[MyViewController alloc] init];

UINavigationController *nc = [[UINavigationController alloc] myViewController];
nc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:nc animated:YES];

When the viewController is presented, the background of it's view is just black. How can I setup it's view to fill-out the screen with an empty view -- just like when the UIViewController is setup in a Storyboard?

I've tried adding the following to the viewDidLoad, but the view is still black:

self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

By default a VC's view gets created in -loadView which you usually neither call, nor override. It gets called automatically the first time you request the the VC's view property.
The view's size is automatically set to the 'empty space', like everything except for the status bar without a NavigationController, minus the navbar when using one etc. You shouldn't worry about its size - usually it's just fine.

You can add your own views in -viewDidLoad and remove them again (for low-memory reasons) in -viewDidUnload .


你可以添加一个带有自定义图像的UIImageView,然后将其发送回来,以便在你的viewcontrollers的viewDidLoad

UIImageView *back = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MyBG"]];
[self.view addSubview:back];
[self.view sendSubViewToBack:back];

如果您正在使用XIB文件,则应通过initWithNibName:bundle方法初始化视图控制器:

链接地址: http://www.djcxy.com/p/15380.html

上一篇: 何时访问UIViewController生命周期中的子视图属性?

下一篇: 如何在UIViewController中设置视图