Creating a view controller without a tip

In AppDelegate, I want to create a subclass of UIViewController and add it. Itself viw will be specified in the code - there is no.

Based on Apple docs I have to use

initWithNibName:nil bundle:nil]; 

and then in the loadView of the controller, I add my subviews, etc.

However, the test code below does not work. I modeled the AppDelegate code on an Apple PageControl demo , simply because my application implements a similar structure (in particular, the base controller to control the scroll view, and an array of another controller to build pages).

But I suspect my AppDelegate code is a problem, as logging proves that initWithNibName :: and loadView are both fires. The application, as shown below, starts, but the screen is blank. I expect a green look with a label.

Appdelegate

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ScrollerController *controller = [[ScrollerController alloc] initWithNibName:nil bundle:nil]; [self.window addSubview:controller.view]; [self.window makeKeyAndVisible]; return YES; } 

ScrollerController (subclass of UIViewController)

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)loadView{ CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame]; UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame]; contentView.backgroundColor = [UIColor greenColor]; self.view = contentView; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 40, 100, 40)]; [label setText:@"Label created in ScrollerController.loadView"]; [self.view addSubview:label]; } 
+4
source share
2 answers

Try using: self.window.rootViewController = controller; instead of [self.window addSubview:controller.view];

Note that you must also @synthesize window; and create it self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

+5
source

Instead of initWithNibNamed: just use alloc and init or any other designated initializer for the view controller. Below is an example from project

 hoverViewController=[[BDHoverViewController alloc] initWithHoverStatusStyle:BDHoverViewStatusActivityProgressStyle]; self.window.rootViewController=hoverViewController; [self.window makeKeyAndVisible]; 

also the correct form (at present anyways) for adding a root view controller to the window in the application’s directory is as follows:

 self.window.rootViewcontroller=controller; [self.window makeKeyAndVisible]; 

You do not need to add a view to the window. The above code does this automatically.

Good luck

T

+4
source

Source: https://habr.com/ru/post/1415244/


All Articles