美文网首页SwiftUI
监听界面方向

监听界面方向

作者: 王勋才 | 来源:发表于2021-11-17 22:19 被阅读0次
    / / from https://github.com/jaywcjlove/swiftui-example
    import SwiftUI
    
    // 我们的自定义视图修饰符可跟踪旋转并调用我们的操作
    struct DeviceRotationViewModifier: ViewModifier {
        let action: (UIDeviceOrientation) -> Void
    
        func body(content: Content) -> some View {
            content
                .onAppear()
                .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
                    action(UIDevice.current.orientation)
                }
        }
    }
    
    // 一个视图包装器,使修改器更易于使用
    extension View {
        func onRotate(perform action: @escaping (UIDeviceOrientation) -> Void) -> some View {
            self.modifier(DeviceRotationViewModifier(action: action))
        }
    }
    
    // 示例视图以演示解决方案
    struct ContentView: View {
        @State private var orientation = UIDeviceOrientation.unknown
    
        var body: some View {
            Group {
                if orientation.isPortrait {
                    Text("Portrait")
                } else if orientation.isLandscape {
                    Text("Landscape")
                } else if orientation.isFlat {
                    Text("Flat")
                } else {
                    Text("Unknown")
                }
            }
            .onRotate { newOrientation in
                orientation = newOrientation
            }
        }
    }
    
    

    相关文章

      网友评论

        本文标题:监听界面方向

        本文链接:https://www.haomeiwen.com/subject/kqwjtrtx.html