簡體   English   中英

Swift:設置rootViewController不起作用?

[英]Swift: Setting rootViewController not working?

我正在嘗試啟動一個新的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.
    }
    */

}

我錯過了一步嗎? 啟動模擬器時,我沒有看到任何警告/錯誤

在該行中:

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

如果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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM