对于UINavigationController和UIViewController,在swift 4中禁用屏幕方向

问题描述 投票:2回答:2

嗨,我试图在我的项目中的一个视图控制器中停止自动旋转。在下面的快照中,enter image description here

我有一个起始的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 9swift 4.0。任何建议将不胜感激。

此致,neena

swift uiviewcontroller uinavigationcontroller orientation auto-rotation
2个回答
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
}

0
投票

我遇到了同样的问题。我查看堆栈溢出并尝试了许多解决方案,但没有一个工作。我在苹果开发者论坛上找到了这个解决方案,它就像一个魅力。

我在这里添加他们的解决方案,希望将来更容易找到其他人,将author归功于their post,并链接到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") } }

添加到AppDelegate文件:

override func viewDidAppear(_ animated: Bool) {

    super.viewDidAppear(animated)

    AppDelegate.AppUtility.lockOrientation(.portrait)

}

override func viewWillDisappear(_ animated: Bool) {

    super.viewWillDisappear(animated)

    AppDelegate.AppUtility.lockOrientation(.all)

}

添加到要强制方向的viewcontroller:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.