RootViewController 在其委托外部访问时不会添加子视图

RootViewController won't add subview when accessed outside its delegate

本文关键字:添加 视图 访问 外部 RootViewController      更新时间:2023-10-16

我编译了这段代码,没有错误,但我无法显示welcomeUIView

是的,当我在didFinishLaunchingWithOptions中移动它时,它会显示出来。但是为什么我不能按照我想要的方式去做呢?

控制台在这里:

didFinishLaunchingWithOptions
view()
finished

代码:

AppDelegate.h

#import <UIKit/UIKit.h>
static UIWindow *window;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@end 

AppDelegate.mm

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
std::cout<<"didFinishLaunchingWithOptions"<<std::endl;
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
window.rootViewController = [[UIViewController alloc] init];
view *v = new view();
v->set();
// Override point for customization after application launch.
window.backgroundColor = [UIColor whiteColor];
[window makeKeyAndVisible];
std::cout<<"finished"<<std::endl;
return YES;
}

视图.mm

#include "view.h"
#include "AppDelegate.h"
#include <UIKit/UIKit.h>
#include <iostream>
void view::set()
{
std::cout<<"view()"<<std::endl;
UIView *welcomeUIView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[welcomeUIView setBackgroundColor:[UIColor darkGrayColor]];
[welcomeUIView setHidden:false];
[window.rootViewController.view addSubview:welcomeUIView];
[window.rootViewController.view bringSubviewToFront:welcomeUIView];
}

错误在于window在标头中被声明为static,因此每个翻译单元都有自己不同的window

您已经在AppDelegate.mm中设置了window变量,但在view.mm中,您有一个不同的window,它仍然为零。如果你想共享window,你应该在你的头中声明是extern,然后在AppDelegate.mm中定义它。

此外,您应该让视图控制器通过子类化UIViewController并重写loadView来设置自己的视图层次结构。

您可以在根视图控制器中轻松添加视图。在viewDidLoad 中执行

-(void)viewDidLoad {
    [super viewDidLoad]; 
    UIView *welcomeView = 
          [[UIView alloc] initWithFrame:self.view.bounds];
    welcomeView.backgroundColor = UIColor.darkGrayColor;
    [self.view addSubview:welcomeView];
}

但是,如果您有状态栏或导航栏,这不会覆盖整个屏幕。相反,您可以将视图添加到self.view.window(使用代码中的CGRect)。