SwiftUI根据横竖屏自动切换布局结构
所属分类:ios | 发布于 2023-04-24
想做个新应用,需要用到横竖屏切换时自动切换布局,查了很多资料都没搞定,最后在Medium上面发现了解决方法。
先看下最终效果
实现步骤如下:
1、自定义一个叫做DetectOrientation的modifer
这个modifier有一个binding类型的属性,和一个NotificationCenter的观察者来订阅屏幕方便变化通知。
struct DetectOrientation: ViewModifier {
@Binding var orientation: UIDeviceOrientation
func body(content: Content) -> some View {
content
.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
orientation = UIDevice.current.orientation
}
}
}
2、为了更方便的使用modifier,创建一个view的扩展
extension View {
func detectOrientation(_ orientation: Binding<UIDeviceOrientation>) -> some View {
modifier(DetectOrientation(orientation: orientation))
}
}
3、在自己的视图中使用自定义的modifier
给视图增加一个orientation的State属性,用来传递给modifier
struct OrientationExample: View {
@State private var orientation = UIDevice.current.orientation
var body: some View {
VStack {
if orientation.isLandscape {
HStack {
Image(systemName: "heart.fill")
Text("DevTechie")
Image(systemName: "heart.fill")
}
.font(.largeTitle)
.foregroundColor(.orange)
} else {
VStack {
Image(systemName: "heart.fill")
Text("DevTechie")
Image(systemName: "heart.fill")
}
.font(.largeTitle)
.foregroundColor(.orange)
}
}.detectOrientation($orientation)
}
}