2015-05-04 96 views
12

我在我的應用程序中進行漫遊(入門流程),我想要一個跳過按鈕。 該按鈕位於viewController上,所以我想到移動到另一個viewController的最佳方式是訪問應用程序委託窗口。Swift - 從viewController訪問AppDelegate窗口

但是,它讓我錯誤地發現AppDelegate.Type沒有名爲「window」的成員。

@IBAction func skipWalkthrough(sender: AnyObject) { 
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    AppDelegate.window!.rootViewController = RootViewController 
} 

這種方法有什麼問題嗎?

在此先感謝!

回答

29

你有一個錯字它應該是appDelegate不是AppDelegate。所以像這樣:

@IBAction func skipWalkthrough(sender: AnyObject) { 
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    appDelegate.window!.rootViewController = RootViewController 
} 
+0

好了吧,有什麼studip錯誤!順便說一句,現在有一個RootViewController的問題,如何訪問此故事板中聲明的視圖控制器?我想創建一個新實例並不是一個好主意?我的意思是RootViewController()導致黑屏,所以應該是另一個等待訪問這樣的控制器 – DCDC

+0

這裏是我如何在我的代碼'let storyboardId =「LoginStoryboardIdentifier」' 'self.window?.rootViewController = self.window? .rootViewController?.storyboard?.instantiateViewControllerWithIdentifier(storyboardId)as? UIViewController' –

+0

完美的工作,但注意到內存消耗,當我用(b)替換根視圖控制器(a)時,我看不到內存減少。 這意味着(a)沒有從記憶中消失,對吧? 如何從內存中擦除它然後顯示(b)控制器 –

1

您正在使用的協議名稱(即AppDelegate),而不是實例:

應該是:

appDelegate.window!.rootViewController = RootViewController 
14

斯威夫特3+

let appDelegate = UIApplication.shared.delegate as? AppDelegate 
    let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) 
    let homeController = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController 
    appDelegate?.window?.rootViewController = homeController 
+0

我使用您的代碼推動,但回去視圖控制器.. –

5

Swift 3

這是一個更好的辦法:

if let window = NSApplication.shared().windows.first { 
     window.acceptsMouseMovedEvents = true; 
    } 
0

這對於解決方案的工作: 登錄/註冊後以編程方式添加的UITabBarController

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    appDelegate.window!.rootViewController = tabs //() 
    appDelegate.window!.makeKeyAndVisible() 
+0

雖然此代碼段是受歡迎的,並可能提供一些幫助,它會[如果包含* how *和* why *的解釋](// meta.stackexchange.com/q/114762),則可以大大改善此問題。請記住,你正在爲將來的讀者回答這個問題,而不僅僅是現在問的人!請編輯您的答案以添加解釋,並指出適用的限制和假設。 –

相關問題