【问题标题】:programmatically add a UIButton to rootview, what am I doing wrong?以编程方式将 UIButton 添加到 rootview,我做错了什么?
【发布时间】:2011-09-23 12:53:02
【问题描述】:

我有一个新设置的应用程序,只有一个窗口和一个根视图(来自 XCode 提供的 iOS 单视图应用程序模板)。

现在我尝试向它添加一个按钮。

相应的代码如下所示:

- (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 currentDevice] 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;
}

当我启动应用程序时,我只能看到空视图。

但是,当注释掉将视图作为根添加到窗口中而不是直接将按钮添加到窗口中的行时,我可以看到按钮就好了。

那么为什么这不适用于视图?

【问题讨论】:

    标签: ios uiview uiviewcontroller uikit uibutton


    【解决方案1】:

    问题在于,即使在分配 viewController 之前,您也将 button0 添加为 self.viewController.view 的子视图。

    当您调用 addSubview: 方法时,self.viewControllernil。因此,按钮没有添加到 viewController。您应该在分配 viewController 后添加按钮。

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

    【讨论】:

    • 哇,看来我已经瞎了。
    【解决方案2】:

    首先,创建根视图控制器,然后添加子视图。你反其道而行之。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多