gpt4 book ai didi

ios - 以编程方式将 UIButton 添加到 rootview,我做错了什么?

转载 作者:行者123 更新时间:2023-11-29 04:58:16 25 4
gpt4 key购买 nike

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

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

相应的代码如下所示:

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

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

但是,当注释掉该行(将 View 作为根添加到窗口中,而不是直接将按钮添加到窗口中)时,我就可以很好地看到该按钮。

那么为什么这不适用于 View 呢?

最佳答案

问题是,即使在分配 viewController 之前,您也将 button0 添加为 self.viewController.view 的 subview 。

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

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

关于ios - 以编程方式将 UIButton 添加到 rootview,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7529245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com