当我尝试键入返回我的功能时,我在AppDalgate.Swift中收到此错误
AppDalgate.Swift
func application (application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
return checkOrientation(self.window?.rootViewController)
}
此代码适用于ViewController.Swift
func checkOrientation(viewController:UIViewController?)-> Int{
if(viewController == nil){
return Int(UIInterfaceOrientationMask.All.rawValue)//All means all orientation
}else if (viewController is LoginViewController){
return Int(UIInterfaceOrientationMask.Portrait.rawValue)//This is sign in view controller that i only want to set this to portrait mode only
}else{
return checkOrientation(viewController!.presentedViewController)
}
}
答案 0 :(得分:3)
您的App Delegate无权访问View Controller中的功能。如果你想实现这一点,一个选择是将一个变量添加到AppDelegate
并将其设置为实例化ViewController
,如下所示:
//Add this to your AppDelegate Outside of the methods.
var vc = ViewController()
执行此操作后,您可以从AppDelegate访问ViewController的方法,如下所示:
//Inside a method of AppDelegate
//Replace ... with your parameters
vc.checkOrientation(...)
但是,请记住,这与您的应用在应用完成启动时将使用的ViewController
类的实例不同。因此,如果您尝试使用引用应用程序启动后添加的数据的方法,则该方法将无效。
另外,请注意,出于性能原因,AppDelegate
应尽可能简洁。
此外,您应该将checkOrientation
功能更改为:
func checkOrientation(viewController:UIViewController?)-> UIInterfaceOrientationMask {
if viewController is LoginViewController {
return UIInterfaceOrientationMask.Portrait
} else {
return UIInterfaceOrientationMask.All
}
}
最后,请考虑完全删除checkOrientation
并将其逻辑放在supportedInterfaceOrientationsForWindow
中。示例:
func application (application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
if self.window?.rootViewController is LoginViewController {
return UIInterfaceOrientationMask.Portrait
} else {
return UIInterfaceOrientationMask.All
}
}