loadView

  1. Action: Loads the view of the controller

  2. When called: This is called when the controller’s view is first used

  3. Usage scenario: Call this method whenever you want to customize the controller’s view

Accessing the View of the controller is equivalent to calling the View GET method of the controller


-(UIView *)view{
    if(_view == nil){
        [self loadView];
        [self viewDidload];
        
    }
    return _view;
}

Copy the code

The process for the controller to load a view

  • The init method of the controller calls the initWithNibName method underneath

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

Note:

  • The nibName is not specified. No custom loadView method; Controller to… Named after the Controller

  • Judgment principle:

  • 1. Check if nibName is specified. If so, load niB

  • 2, check whether there is a xiB with the same name as the Controller, but the name of the xiB does not contain the Controller xib, if there is a load

  • 3. If the second step does not specify a xiB with the same name as the controller class, load it

  • 4. If there is no XIB describing the view of the controller, the XIB is not loaded

MyViewController loads the view processing

  • Check if the xibName is specified and load the xiB

  • Check if there is a XIB with the same name as the controller class, but without the name controller

  • Check if there is a xiB with the same name as the controller class

  • Simply create an empty XIB

example

ViewController *vc = [[ViewController alloc] init]; vc.view.backgroundColkor = [UIColor redColor]; self.window.rootViewController = vc; [pself.window makeKeyAndVisable]; //ViewController -(UIView *)view{if(! _view){ [self loadView]; [self viewDidLoad]; } } -(void)loadView{ UIView*view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds]; view.backgroundColor = [UIColor greenColor]; self.view = view; } -(void)viewDidload{ [super viewDidload]; self.view.backgroundColor = [UIColor brownColor]; }Copy the code

What is the color of the interface?

Probably a lot of people will go back to green. The answer is red

According to? In AppDelegate, vc.view.backgroundcolor is a call to the getter method of vc’s view, and inside the getter method it checks if _view exists, and if it doesn’t, it creates a new UIView, A new view is created using the [self loadView] method, which calls viewDidLoad directly. If it exists, it returns, so the interface is green, then brown and then red

Here’s an official explanation