在 iOS swift 5 專案中,我只需要在一個場景中支持多個設備方向。
我有以下要求:
- 如果設備旋轉,則不應更改設備方向。
- 如果點擊按鈕,則應更改設備方向(向左旋轉)
這意味著只有一個UIViewController用戶應該能夠通過點擊按鈕手動更改設備方向,但旋轉設備不應該做任何事情。
uj5u.com熱心網友回復:
實作此目的的一種簡單方法是在(_:supportedInterfaceOrientationsFor:)上設定您支持的方向AppDelegate
在那里創建一個區域變數
var orientation: UIInterfaceOrientationMask = .portrait
然后將該變數作為支持的方向回傳
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return orientation
}
在ViewController您想通過觸摸按鈕旋轉的情況下,您可以更改應用程式委托上支持的方向,而不是強制更改設備方向以便旋轉視圖
private func changeSupportedOrientation() {
let delegate = UIApplication.shared.delegate as! AppDelegate
switch delegate.orientation {
case .portrait:
delegate.orientation = .landscapeLeft
default:
delegate.orientation = .portrait
}
}
@IBAction func rotateButtonTapped(_ sender: UIButton) {
changeSupportedOrientation()
switch UIDevice.current.orientation {
case .landscapeLeft:
UIDevice.current.setValue(UIDeviceOrientation.portrait.rawValue, forKey: "orientation")
default:
UIDevice.current.setValue(UIDeviceOrientation.landscapeLeft.rawValue, forKey: "orientation")
}
}
這將強制設備的方向改變,然后旋轉您的視圖。如果您再次點擊按鈕,方向將回到.portrait
請小心使用它,因為您需要真正考慮您的導航堆疊,以確保只有導航堆疊的頂部支持旋轉,并且只有在將方向設定回原始后才能從導航堆疊彈出.portrait。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/326255.html
上一篇:SwiftUI鍵盤單詞建議欄
