Force landscape mode in one ViewController using Swift

后端 未结 19 1246
情书的邮戳
情书的邮戳 2020-12-02 07:44

I am trying to force only one view in my application on landscape mode, I am calling

override func shouldAutorotate() -> Bool {
    print(\"shouldAutoro         


        
19条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 08:18

    Swift 3. This locks the orientation each time the user re-opens the app.

    class MyViewController: UIViewController {
        ...
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Receive notification when app is brought to foreground
            NotificationCenter.default.addObserver(self, selector: #selector(self.onDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
        }
    
        // Handle notification
        func onDidBecomeActive() {
            setOrientationLandscape()
        }
    
        // Change orientation to landscape
        private func setOrientationLandscape() {
            if !UIDevice.current.orientation.isLandscape {
                let value = UIInterfaceOrientation.landscapeLeft.rawValue
                UIDevice.current.setValue(value, forKey:"orientation")
                UIViewController.attemptRotationToDeviceOrientation()
            }
        }
    
        // Only allow landscape left
        override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
            return UIInterfaceOrientationMask.landscapeLeft
        }
    
        /*
        // Allow rotation - this seems unnecessary
        private func shouldAutoRotate() -> Bool {
            return true
        }
        */
        ...
    }
    

提交回复
热议问题