RootViewController 在其委托外部访问时不会添加子视图
RootViewController won't add subview when accessed outside its delegate
我编译了这段代码,没有错误,但我无法显示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)。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 视图中的参数推导失败:take_while
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- 在另一个类视图中添加最多2个图表的正确方法是什么
- MFC MDI 向文档添加第二个视图
- 如何在移动列表视图中添加滚动条?并且用户只能垂直滚动特定区域
- 为 Web 视图添加 UI 栏按钮项,但应用崩溃
- WinRT W8 在C++中创建 Web 视图并将其添加到主视图
- 无法将目录添加到视图中
- 如何在mainwindow.cpp中将场景添加到视图中
- RootViewController 在其委托外部访问时不会添加子视图
- 在Qt creator中只添加可读行到表视图
- 将行动态添加到表视图中