【发布时间】:2015-07-18 13:50:58
【问题描述】:
在常规设置中,我允许纵向和横向左、横向模式。我想关闭横向模式。在 viewController 我写了这段代码:
override func shouldAutorotate() -> Bool {
return false
}
但是,自动旋转会忽略此功能。如何快速禁用和启用自动旋转? IOS编程
【问题讨论】:
在常规设置中,我允许纵向和横向左、横向模式。我想关闭横向模式。在 viewController 我写了这段代码:
override func shouldAutorotate() -> Bool {
return false
}
但是,自动旋转会忽略此功能。如何快速禁用和启用自动旋转? IOS编程
【问题讨论】:
它可能是正确的代码,但不在正确的视图控制器中。例如,如果 View Controller 嵌入在 UINavigationController 中,则导航控制器仍然可以旋转,从而导致 View Controller 仍然旋转。这真的取决于你的具体情况。
【讨论】:
我有同样的问题,我已经解决了。
关注-
info --> 自定义 ios 目标属性 --> 支持接口 Orinetations。并删除![删除 - 横向(左主页按钮),横向(右主页按钮),横向(顶部主页按钮)][1]
这会对你有所帮助?
【讨论】:
您可以通过创建 UINavigationController 的子类并在其中覆盖 should AutoRotate 函数,然后
为你想要自动旋转的viewControllers返回true
import UIKit
class CustomNavigationController: UINavigationController {
override func shouldAutorotate() -> Bool {
if !viewControllers.isEmpty {
// Check if this ViewController is the one you want to disable roration on
if topViewController!.isKindOfClass(ViewController) { //ViewController is the name of the topmost viewcontroller
// If true return false to disable it
return false
}
}
// Else normal rotation enabled
return true
}
}
如果您想禁用整个导航控制器的自动旋转,请删除 if 条件并始终返回 false
【讨论】:
扩展 Josh Gafni 的回答和 user3655266,这个概念也扩展到了视图控制器。
如果我们有一个 UIViewController 是视图层次结构中另一个 UIViewController 的子级,则将子级的 shouldAutorotate() 覆盖为 false 可能仍会旋转,因为它的父级控制器可能仍会返回 true 。同样重要的是要知道,即使正在显示子 VC,仍然会调用父级的 shouldAutoRotate 函数。因此控件应该在那里。
斯威夫特 5
class ParentViewController:UIViewController{
override func shouldAutorotate() -> Bool {
// Return an array of ViewControllers that are children of the parent
let childViewControllersArray = self.children
if childViewControllersArray.count > 0 {
// Assume childVC is the ViewController you are interested in NOT allowing to rotate
let childVC = childViewControllersArray.first
if childVC is ChildViewController {
return false
}
}
return true
}
}
** 也可以这样做只允许某些手机方向**
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// This function is called on the parent's controller whenever the child of this parent is trying to rotate
let childrenVCArray = self.children
if childrenVCArray.count > 0 {
// assuming the array of the first element is the current childVC
let topMostVC = childrenVCArray[0]
if topMostVC is ChildViewController {
// Assuming only allowing landscape mode
return .landscape
}
}
// Return portrait otherwise
return .portrait
}
【讨论】:
我不确定 shouldAutorotate() 功能是否仍然在 2021 年的 swift 5 中启用。但是我建议调用以下函数之一作为管理 ViewController 旋转的标准过程的一部分。 (apple developer webside 中的“处理视图旋转”部分,例如 preferredInterfaceOrientationForPresentation
【讨论】: