我有 2 个 View Controller ,VC1 和 VC2。
VC1 目前以模态方式呈现 VC2。
VC1 只有方向应该是纵向,但 VC2 可以有所有方向。
问题是当我在 VC2 中旋转到横向模式然后关闭时,VC1 也处于横向模式!那永远不应该发生!
注意:没有 Navigation Controller 或 UITabbarcontroller
我正在下面添加我的代码。
应用:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if let rootViewController = self.topViewControllerWithRootViewController(rootViewController: window?.rootViewController) {
if (rootViewController.responds(to: Selector(("canRotate")))) {
// Unlock landscape view orientations for this view controller
return .allButUpsideDown
}
}
// Only allow portrait (standard behaviour)
return .portrait;
}
private func topViewControllerWithRootViewController(rootViewController: UIViewController!) -> UIViewController? {
if (rootViewController == nil) { return nil }
if (rootViewController.isKind(of: (UITabBarController).self)) {
return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UITabBarController).selectedViewController)
} else if (rootViewController.isKind(of:(UINavigationController).self)) {
return topViewControllerWithRootViewController(rootViewController: (rootViewController as! UINavigationController).visibleViewController)
} else if (rootViewController.presentedViewController != nil) {
return topViewControllerWithRootViewController(rootViewController: rootViewController.presentedViewController)
}
return rootViewController
}
VC2中的代码:
override func viewDidLoad() {
super.viewDidLoad()
UIDevice.current.setValue(Int(UIInterfaceOrientation.portrait.rawValue), forKey: "orientation")
}
func canRotate() -> Void {}
链接到我寻求帮助并找到这段代码的地方 Website where I found Code
非常感谢您的帮助!
最佳答案
您需要按照以下步骤锁定特定 ViewController 的旋转:-
第 1 步:
创建项目时,允许所有方向。不要选择下图中的任何内容。
第 2 步:
如果您希望 VC1 仅实现纵向方向,则在您的 ViewController 类中添加以下两个函数
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.all //return the value as per the required orientation
}
override var shouldAutorotate: Bool {
return false
}
第 3 步:
如果您希望 VC2 具有所有方向,则不要为其添加任何代码。
所以结论:-
在项目设置中,允许整个项目的所有方向。限制应该在 ViewController 级别而不是项目级别。
如果您希望任何 VC 具有所有方向,那么请不要编写任何代码。
如果您希望任何 VC 具有特定的方向,请实现上面的两个功能。
关于ios - 如何为某些 View Controller 锁定 iPhone 的方向 - Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43795577/