[英]How to unlock Orientation Lock SwiftUI
環境:SwiftUI 與 Swift 5.5, Xcode 13
對於我的應用程序,我需要它鎖定某些方向,然后從該方向解鎖。 有一段時間,按照這個Stack Overflow 答案的想法,它工作得很好。 目前,一旦我將它鎖定到某個方向,解鎖它似乎什么都不做,並且不再調用檢查 supportedInterfaceOrientations 的 AppDelegate function。
這是我的 AppDelegate 代碼:
class AppDelegate: NSObject, UIApplicationDelegate {
static var orientationLock = UIInterfaceOrientationMask.allButUpsideDown
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return AppDelegate.orientationLock
}
}
這是包含 AppDelegate 的我的應用程序的入口點:
struct OrientationApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
這是鎖定/解鎖方向的應用程序的基本部分:
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, world!")
Button("Lock Portrait") {
AppDelegate.orientationLock = .portrait
}
Button("Lock Landscape") {
AppDelegate.orientationLock = .landscape
}
Button("Unlock Orientation") {
AppDelegate.orientationLock = .allButUpsideDown
}
}
}
}
旋轉可以正常工作,當我單擊“鎖定方向”時,它會按預期阻止它旋轉,但是當我單擊“解鎖方向”時,它似乎不起作用。 我仍然無法讓它旋轉。 我嘗試將 AppDelegate 更改為 ObservableObject 並獲得相同的行為。 另外,讓我知道 iOS 15 或 iOS 16 是否有更好的方法來處理 SwiftUI 中的方向。 這是我能夠讓它發揮作用的唯一方法。
回調application:supportedInterfaceOrientationsFor
在每次方向更改時被調用,因此當您更改自定義屬性時,它只是屬性值,沒有其他真正改變。
我們需要以某種方式通知運行時它應該根據方向重新驗證。
這是一個可能的解決方案。 使用 Xcode 13.4 / iOS 15.5 測試
class AppDelegate: NSObject, UIApplicationDelegate {
static var orientationLock = UIInterfaceOrientationMask.allButUpsideDown {
didSet {
// post notification so layout be revalidated
// calling corresponding app delegate as well
NotificationCenter.default.post(name: UIDevice.orientationDidChangeNotification, object: nil)
}
}
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.