2015-10-17 65 views
0

我想开始一个新的Swift项目。这是我第一次尝试以编程方式创建视图。但它甚至不像我的控制器正在加载?我看到的只是启动屏幕,然后在加载到模拟器上时出现黑屏。Swift:设置rootViewController不工作?

这是我的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() 
    } 

} 

的MapViewController:

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. 
    } 
    */ 

} 

我失踪了一步?我没有看到任何警告/错误,当我启动模拟器

回答

0

在行:

self.window?.rootViewController = self.rootViewController() 

如果window属性为nil,它不会执行你的self.rootViewController()电话。你可以阅读更多关于calling methods with optional chaining in the documentation的详细信息。

如果您尝试在代码中创建初始用户界面,则需要创建一个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 
} 
+0

在不工作Swift 3.0 –

+0

@MayankJain它为什么会这样,它是从一年前开始的。 –

+0

是的,你是对的...我在Swift 3面临同样的问题在这里看到我的问题https://stackoverflow.com/questions/40085021/initial-rootviewcontroller-is-not-setting-in-swift-3-0 –