我正在尝试启动一个新的 Swift 项目。这是我第一次尝试以编程方式创建视图。然而,我的控制器看起来根本没有被加载?我所看到的只是启动屏幕,然后当我将其加载到模拟器上时出现黑屏。
这是我的 AppDelegate:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NSLog("zrrrzz") // <------------------------------ Prints properly
self.window?.rootViewController = self.rootViewController()
return true
}
private func rootViewController() -> UIViewController {
NSLog("zzz") // <---------------------------------- Does not print ????
return MapViewController.init()
}
}
地图视图控制器:
import UIKit
class MapViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I am a test label"
self.view.backgroundColor = UIColor.whiteColor()
self.view.addSubview(label)
NSLog("heyyyy!!") //<------------------------------ Also doesn't print ??
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
我是不是少了一步?启动模拟器时我没有看到任何警告/错误
在行中:
self.window?.rootViewController = self.rootViewController()
If the window
财产是nil
,它不会执行你的self.rootViewController()
称呼。您可以阅读更多有关调用文档中带有可选链的方法了解详情。
如果您尝试在代码中创建初始用户界面,则需要创建一个UIWindow
实例并将其分配给self.window
。使用情节提要时,这是自动为您完成的。
免责声明:我还没有在 iOS 的几个版本中编写过这段代码,所以这可能不完全正确,但它会让你朝着正确的方向前进:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let applicationFrame = UIScreen.mainScreen().applicationFrame
let window = UIWindow(frame: applicationFrame)
window.rootViewController = self.rootViewController()
window.makeKeyAndVisible()
self.window = window
return true
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)