首页 > 解决方案 > In Swiftui How to automatically close modal with rotation to landscape

问题描述

I currently use an landscape environmentobject based on this code - https://stackoverflow.com/a/58503841/412154

Within my view I have modals that appear and disappear appropriately using @State/@Binding depending on a "Done" Button press. My app does show a different view when rotated to landscape and I would like for the modal to dismiss automatically on the rotation, but couldn't figure out how to change the @binding var based on another @ennvironmentobject

Here is a simplified sample of my Modal View

struct StepsView: View {
    @Binding var isPresented:Bool
    @EnvironmentObject var orientation:Orientation

    var body: some View {
        VStack(alignment: .center) {
              Text("Step")
              }
             .navigationBarItems(trailing: Button(action: {
                    //print("Dismissing steps view...")
                    self.isPresented = false
                }) {
                    Text("Done").bold()
                })
            }

thanks for any help!

标签: iosswiftxcodeswiftui

解决方案


欣赏@davidev的回答,但我希望每个模态的行为都有点不同,所以我这样做了

struct StepsView: View {
    @Binding var isPresented:Bool
    @EnvironmentObject var orientation:Orientation
    
    private var PortraitView:some View {
        VStack(alignment: .center) {
              Text("Modal")
              }
             .navigationBarItems(trailing: Button(action: {
                    self.isPresented = false
                }) {
                    Text("Done").bold()
                })
            }
    
    
    var body: some View {
        buildView(isLandscape: orientation.isLandScape, isShowing: &isPresented)
    }

    func buildView(isLandscape:Bool, isShowing:inout Bool) -> AnyView {

        if !isLandscape {
            return AnyView(PortraitView)
        } else {
            isShowing = false
            return AnyView(EmptyView())
        }
    }

推荐阅读