SwiftUI根据横竖屏自动切换布局结构

所属分类:ios | 发布于 2023-04-24 15:13:47

想做个新应用,需要用到横竖屏切换时自动切换布局,查了很多资料都没搞定,最后在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)
    }
}

文哥博客(https://wenge365.com)属于文野个人博客,欢迎浏览使用

联系方式:qq:52292959 邮箱:52292959@qq.com

备案号:粤ICP备18108585号 友情链接