开发者

programmatically add a UIButton to rootview, what am I doing wrong?

I have freshly setup app, just with a window an a root view (from the iOS single view application template, provided by XCode).

Now I try to add a button to it.

The according code looks like this:

- (BOOL) application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UIButton* button0 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button0.frame = CGRectMake(140, 230, 40, 20);
    [button0 setTitle:@"Exit" forState:UIControlStateNormal];
    [button0 addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    [self.viewController.view addSubview:button0];

    if([[UIDevice currentDev开发者_如何学运维ice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
    else
        self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

When I start the app, I can only see the empty view.

However, when comment out the line, which adds the view as root to the window and instead directly add the button to the window, then I can see the button just fine.

So why isn't this working with the view?


The problem is that, you are adding button0 as subview of self.viewController.view even before allocating the viewController.

By the time you call addSubview: method, self.viewController is nil. So, the button is not added to the viewController. You should add the button after you allocate the viewController.

self.viewController = [[ViewController alloc]...
[self.viewController.view addSubview:button0];


At first, create the root viewcontroller, later add subviews to it. You did it the other way round.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜