首页 文章

强制进行横向模式而不设置自动旋转

提问于
浏览
0

我有一个简单的例子:

enter image description here

视图中间的一个按钮 . 我想按下该按钮强制横向模式,然后再次按下强制纵向模式,但我不希望它自动旋转 . 我知道如果我设置 shouldAutorotate -> true ,它会起作用,但就我而言,我不想要自动旋转模式 .

class ViewController: UIViewController {

    var isLanscape = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func rotate(_ sender: Any) {
        isLanscape = !isLanscape
        if isLanscape == true {
            let value = UIInterfaceOrientation.landscapeRight.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        } else {
            let value = UIInterfaceOrientation.portrait.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
        }

    }

    override var shouldAutorotate: Bool {
        return false
    }
}

enter image description here

1 回答

  • 1

    最后,我找到了这种情况的解决方案 .

    如果 shouldAutorotate -> false ,你永远无法旋转屏幕,所以我在这里做了一些技巧 .

    class ViewController: UIViewController {
    
        var isLanscape = false
        var shouldRotate = false
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        @IBAction func rotate(_ sender: Any) {
            isLanscape = !isLanscape
            shouldRotate = true
            if isLanscape == true {
                let value = UIInterfaceOrientation.landscapeRight.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
            } else {
                let value = UIInterfaceOrientation.portrait.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
            }
            self.shouldRotate = false
        }
    
        override var shouldAutorotate: Bool {
            let orientation = UIDevice.current.value(forKey: "orientation") as! Int
            if (orientation == 1 || orientation == 3) && shouldRotate == true {
                return true
            } else {
                return false
            }
        }
    
        override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
            return [.portrait, .landscapeRight]
        }
    }
    

相关问题