Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a view controller without a nib

In AppDelegate, I want to create a UIViewController subclass and add it's view. The viw itself will be specified in code - there is no nib.

Based on the apple docs, I should use

initWithNibName:nil bundle:nil];

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

However, the follwing test code below does not work for me. I modelled the AppDelegate code on Apple's PageControl demo, simply because my app will implement a similar structure (specifically a base controller to manage a paged scroll view, and an array of other controller's to build the pages).

But I suspect my AppDelegate code is the problem, since logging proves that initWithNibName:: and loadView both fire. The app as below runs, but the screen is blank. I am expecting a green view 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 (the UIViewController subclass)

- (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];
}
like image 743
Ben Packard Avatar asked Jan 16 '23 13:01

Ben Packard


1 Answers

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

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

like image 193
Sulthan Avatar answered Jan 21 '23 02:01

Sulthan