我有一个简单的例子:
视图中间的一个按钮。我想按下该按钮强制横向模式,然后再次按下强制纵向模式,但我不希望它自动旋转。我知道如果我设置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
}
}
答案 0 :(得分: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]
}
}