您好我正试图在我的项目中的一个视图控制器中停止自动旋转。在下面的快照中,
我有一个UINavigationController
,然后是UIViewController
。我已经实现了以下代码来停止自动旋转:
extension UINavigationController {
override open var shouldAutorotate: Bool {
get {
return false
}
}
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get {
return UIInterfaceOrientationMask.landscape
}
}}
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override open var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask
{
return .landscape
}
}
但是上面的代码似乎没有调用,也没有产生任何影响。我正在使用Xcode 9
和swift 4.0
。
任何建议都将不胜感激。
此致 NEENA
答案 0 :(得分:1)
创建一个类并将其设置为UINavigationController
,然后在Storyboard / XIB中使用这个新类
在你的扩展程序中:
class NavigationController: UINavigationController {
override var shouldAutorotate: Bool {
return topViewController?.shouldAutorotate ?? super.shouldAutorotate
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return topViewController?.supportedInterfaceOrientations ?? super.supportedInterfaceOrientations
}
}
在您的控制器中:
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
答案 1 :(得分:0)
我遇到了同样的问题。我查看堆栈溢出并尝试了许多解决方案,但没有一个工作。我在苹果开发者论坛上找到了这个解决方案,它就像一个魅力。
我在这里添加了他们的解决方案,希望将来能够更轻松地找到其他人,为author提供信用,并链接到their post。
添加到您的AppDelegate文件:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientationLock
}
struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
添加到要强制定位的viewcontroller:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
AppDelegate.AppUtility.lockOrientation(.portrait)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
AppDelegate.AppUtility.lockOrientation(.all)
}
答案 2 :(得分:0)
这只是对TagTaco上面答案的澄清。
创建自定义类
class CustomUINavigationController: UINavigationController {
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
}
现在您可以创建一个像这样的导航控制器:
let navController = CustomUINavigationController(rootViewController: YourController())
希望它可以帮助某人。 干杯。