![](/img/trans.png)
[英]Accessing locaitonManager from both AppDelegate and ViewController
[英]Swift - Accessing AppDelegate window from viewController
我在我的應用程序中進行了演練(入職流程),並且我想要一個跳過按鈕。 該按鈕位於 viewController 上,所以我發現移動到另一個 viewController 的最佳方法是訪問應用程序委托窗口。
但是,它不斷給我一個錯誤,即 AppDelegate.Type 沒有名為“window”的成員。
@IBAction func skipWalkthrough(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
AppDelegate.window!.rootViewController = RootViewController
}
這種方法有什么問題嗎?
提前致謝!
你有一個錯字,它應該是appDelegate
而不是AppDelegate
。 所以像這樣:
@IBAction func skipWalkthrough(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = RootViewController
}
斯威夫特 3.2
@IBAction func skipWalkthrough(_ sender: AnyObject) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window!.rootViewController = controller
}
這適用於有或沒有 Storyboard,它適用於Swift 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
斯威夫特 3
這是一個更好的方法:
if let window = NSApplication.shared().windows.first {
window.acceptsMouseMovedEvents = true;
}
您還可以使用條件綁定來訪問window
。
if let window = UIApplication.shared.windows.first {
// use window here.
}
appDelegate.window!.rootViewController
在Swift 5 中不起作用
這是工作代碼
添加以下擴展名
extension UIWindow {
static var key: UIWindow! {
if #available(iOS 13, *) {
return UIApplication.shared.windows.first { $0.isKeyWindow }
} else {
return UIApplication.shared.keyWindow
}
}
}
用
let mainSB = UIStoryboard(name: "Main", bundle: nil)
if let RootVc = mainSB.instantiateViewController(withIdentifier: "NavigationController") as? UINavigationController{
UIWindow.key.rootViewController = RootVc
}
UIWindow.key // to access only window
您正在使用協議名稱(即AppDelegate
)而不是實例:
應該:
appDelegate.window!.rootViewController = RootViewController
您可以從應用程序的任何位置訪問標簽欄。 下面使用:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let tabBarController = appDelegate.window!.rootViewController as? UITabBarController {
if let tabItems = tabBarController.tabBar.items {
let tabItem = tabItems[2]
tabItem.badgeValue = "5" //enter any value
}
}
此解決方案適用於:登錄/注冊后以編程方式添加UITabbarController
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.window!.rootViewController = tabs
appDelegate.window!.makeKeyAndVisible()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.