首页 > 解决方案 > 为什么 Swift 没有正确加载这个视图,而 Objective-C 可以?

问题描述

我尝试在 Swift 中编程,但我未能执行一个简单的程序。只需几行代码即可创建一个带有空视图的窗口。

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;

}

标签: swiftuiviewscaleframeuiwindow

解决方案


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

只需几行代码即可创建一个带有空视图的窗口

但是您正在做的不是如何做到这一点。这是带有一些注释的代码:

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
}

看哪,一个没有故事板的最小正确构建的空窗口应用程序(或者至少,如果它有一个故事板,它会忽略它)。


推荐阅读