Swift:设置rootViewController不工作?

时间:2015-10-17 17:38:08

标签: ios swift

我正在尝试启动一个新的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()
  }

}

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

}

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

1 个答案:

答案 0 :(得分: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
}