iOS模拟器在尝试创建帧时显示空白的白色屏幕

uklbhaso  于 2023-05-19  发布在  iOS
关注(0)|答案(1)|浏览(174)

第四章大宅男牧场:iOS编程第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
iq3niunx

iq3niunx1#

如果使用应用程序场景,则会忽略在应用程序代理中手动创建的窗口(* 准确地说,它在很短的时间内保持关键窗口,直到场景使其自己的窗口成为关键窗口 *)。因此,您应该附加在场景代理的-[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;
}

..或者去掉应用程序中的场景委托(您可以参考this question下的讨论以了解如何做到这一点的更多细节),并使其与旧的好应用程序委托的窗口一起工作。请注意,在这种情况下,如果没有指定rootViewController,您将无法使用该窗口,因此您至少需要设置一个虚拟控制器:

_window.rootViewController = [UIViewController new];

相关问题