Apple 遗漏的视图修饰符。SwiftInterfaceOrientation 允许你轻松指定你的 SwiftUI 视图支持的屏幕方向。
将 .interfaceOrientations
修饰符附加到任何 SwiftUI 视图,以指定该视图支持的界面方向。 只要该视图可见,就允许旋转到指定的方向。
例如,除非切换开关打开,否则以下视图将被限制为 .portrait
方向
import InterfaceOrientation
struct MyView: View {
@State private var isLandscapeAllowed = false
var body: some View {
Toggle("Allow landscape", isOn: $isLandscapeAllowed)
.interfaceOrientations(isLandscapeAllowed ? [.portrait, .landscape] : .portrait)
}
}
使用 @UIApplicationDelegateAdaptor
创建一个应用程序委托,并实现 application(_:supportedInterfaceOrientationsFor:)
private class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
InterfaceOrientationCoordinator.shared.supportedOrientations
}
}
如果多个视图指定了方向,则应用程序支持的方向由最小公分母(即,所有指定方向的交集)定义。
例如,给定以下代码,唯一允许的方向是 .portrait
,因为这是所有视图都支持的唯一方向
VStack {
A().interfaceOrientations([.portrait, .landscape])
B().interfaceOrientations([.portrait, .portraitUpsideDown])
}
当没有视图指定自定义方向时,将使用一组默认方向。
SwiftInterfaceOrientation 尝试从 Info.plist 中读取此集合,但你可以使用 InterfaceOrientationCoordinator.shared.defaultOrientations
手动设置它
视图可以支持默认方向集中不存在的方向。
这意味着,如果一个视图支持 .landscapeLeft
,即使默认方向不包含 .landscapeLeft
,界面也可以旋转到横向。
在 iPad 上运行时,SwiftInterfaceOrientation 需要一些额外的配置才能工作。 你需要执行以下操作之一