swift - 为什么 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;
}
解决方案
我无法解释为什么 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
}
看哪,一个没有故事板的最小正确构建的空窗口应用程序(或者至少,如果它有一个故事板,它会忽略它)。
推荐阅读
- css - 仅使用css就可以定义高度保持自然纵横比的动态图像列?
- google-cloud-platform - 如何连接到谷歌虚拟机实例上的 psql
- haskell - 记录中紧凑函数定义的语法扩展
- dfa - DFA 可以设计为接受任何语言吗?
- c - 使用不分配的二维指针
- angular - 联合类型的类型上不存在 typescript 属性“选项”
- java - 制作杂货篮
- mysql - 1170 - 密钥规范中使用的 BLOB/TEXT 列“XXX”没有密钥长度
- mongodb - MongoDB 为重复文档生成相同的 ObjectID
- c - 直接在 C 中直接将函数的返回(和调用)作为另一个参数传递