2015-10-17 151 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 –