为什么 Swift 没有正确加载此视图,而 Objective-C 可以?

Why did Swift NOT load this view properly, while Objective-C did?

我尝试在Swift中编程,但是我无法执行一个简单的程序。只需几行代码即可创建具有空视图的 window。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.


    self.window = UIWindow(frame: CGRect(x: 0.0, y: 0.0, width: 640.0, height: 960.0))

    let viewController = UIViewController()

    let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 640.0, height: 960.0))

    view.backgroundColor = UIColor.white

    viewController.view = view

    self.window?.rootViewController = viewController

    self.window?.makeKeyAndVisible()

    return true

}

此代码生成了一个未填满屏幕的视图。我尝试了屏幕、框架和比例的边界,不幸的是失败了。

但是当我在 Objective-C 中尝试以下操作时,它 运行 正如预期的那样:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

self.window = [[UIWindow alloc] initWithFrame:CGRectMake(0.0, 0.0,640.0,960.0)];

UIViewController *viewController = [[UIViewController alloc] init];

UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0,640.0,960.0)];

[view setBackgroundColor:[UIColor whiteColor]];

viewController.view = view;

[self.window setRootViewController:viewController];

[self.window makeKeyAndVisible];

return YES;

}

我无法解释为什么 Objective-C 代码会像您预期的那样工作。但我确实知道 Swift 代码有什么问题:

Just few lines of code to create a window with an empty view

但是你正在做的不是怎么做;这是带有一些注入评论的代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: CGRect(x: 0.0, y: 0.0, width: 640.0, height: 960.0))
    // wrong; there is no need to frame the window
    // and if you do frame it, it must be framed to the actual screen size

    let viewController = UIViewController()
    let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 640.0, height: 960.0))
    view.backgroundColor = UIColor.white
    viewController.view = view
    // wrong; you must never assign a view controller a view like this...
    // except in the view controller's own `loadView` method

    self.window?.rootViewController = viewController
    self.window?.makeKeyAndVisible()
    return true
}

所以,根据需要修改:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow()
    let viewController = UIViewController()
    viewController.view.backgroundColor = .white
    self.window?.rootViewController = viewController
    self.window?.makeKeyAndVisible()
    return true
}

瞧,一个没有情节提要的最小正确构造的空 window 应用程序(或者至少,如果它有情节提要,它会忽略它)。