I am trying to pop to the root view controller of the navigation stack from the app delegate and having some problems converting what works in obj-c to swift.
What works in obj-c:
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
[navigationController popToRootViewControllerAnimated:YES];
my attempt at converting:
var navigationController: UINavigationController = self.window?.rootViewController;
navigationController.popToRootViewControllerAnimated(true);
i get an error saying UIViewController? is not convertible to UINavigationController'
How can I fix this?
答案 0 :(得分:6)
There are a few things at play here:
1) rootViewController is going to be returned as an optional as both the window and the rootViewController property are optional. Thus we need to unwrap it to ensure these values are actually there
2) rootViewController is defined as a UIViewController - not the UINavigationController subclass. We need to cast it to a UINavigationController to be able to operate on it as one.
try safely unwrapping the root view controller as a UINavigationController:
if let navigationController = self.window?.rootViewController as? UINavigationController {
navigationController.popToRootViewController(animated: true)
}
答案 1 :(得分:1)
swift 3使用此:
_ = navigationController?.popToRootViewController(animated: true)