在 Big Nerd Ranch:iOS 编程第 4 版 教科书的第 4 章中,我们应该在 AppDelegate.m 文件的视图中间创建一个红色矩形,并将其显示在模拟器中。
我已经逐字复制了代码,当我运行模拟器时,我得到一个像这样的空白屏幕:
我不确定为什么会这样。我已经将
window
的属性放在 AppDelegate.h 文件中,所以我知道这不是原因。
这是 AppDelegate.m 文件中的代码:
//
// AppDelegate.m
// Hypnosister
//
//
//
#import "AppDelegate.h"
#import "BNRHypnosisView.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
CGRect firstFrame = CGRectMake(160, 240, 100, 150);
BNRHypnosisView *firstView = [[BNRHypnosisView alloc]initWithFrame:firstFrame];
firstView.backgroundColor = [UIColor redColor];
[self.window addSubview:firstView];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
#pragma mark - UISceneSession lifecycle
- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}
- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
@end
如果你使用应用程序场景,你在应用程序委托中手动创建的窗口将被忽略(准确地说它在很短的时间内保持关键窗口,直到场景使自己的窗口成为关键窗口)。所以你要么应该附加你在场景委托的
-[UISceneDelegate scene:willConnectToSession:options:]
方法中创建的窗口:
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
UIWindow *window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(160, 240, 100, 150)];
view.backgroundColor = UIColor.redColor;
[window addSubview:view];
window.backgroundColor = UIColor.whiteColor;
[window makeKeyAndVisible];
self.window = window;
}
.. 或者在您的应用程序中删除场景委托(您可以参考 这个问题 下的讨论以获取有关如何执行此操作的更多详细信息)并使其与旧的良好应用程序委托窗口一起使用。请注意,在这种情况下,如果没有指定
rootViewController
,您将无法使用窗口,因此您至少需要设置一个虚拟控制器:
_window.rootViewController = [UIViewController new];