[使用SwiftUI,我们在列表中安装了一个Button。为什么当我点击按钮以显示模态然后再次将其关闭时,模态消失了?

问题描述 投票:1回答:1

我现在正在学习使用Xcode11的正式版本为SwiftUI创建示例代码。我写了一个简单的代码来显示和隐藏模式。此代码将一个按钮添加到列表并显示模式。但是,奇怪的是,关闭后再次轻按按钮时,模态不再显示。

是否有这个或任何解决方案的原因?

[当列表中有一个按钮时发生,但是如果您仅从代码中删除列表,则模态可以显示任意多次。

这是导致该错误的代码。

struct ContentView: View {
  @State var show_modal = false
  var body: some View {
    List {
      Button(action: {
        print("Button Pushed")
        self.show_modal = true
      }) {
        Text("Show Modal")
      }.sheet(isPresented: self.$show_modal, onDismiss: {
        print("dismiss")
      }) {
        ModalView()
      }
    }
  }
}

这是不会引起错误的代码。

struct ContentView: View {
  @State var show_modal = false
  var body: some View {
      Button(action: {
        print("Button Pushed")
        self.show_modal = true
      }) {
        Text("Show Modal")
      }.sheet(isPresented: self.$show_modal, onDismiss: {
        print("dismiss")
      }) {
        ModalView()
      }
  }
}

唯一的区别是是否有列表。

下面是ModalView代码。

struct ModalView: View {
    // 1. Add the environment variable
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        // 2. Embed Text in a VStack
        VStack {
            // 3. Add a button with the following action
            Button(action: {
                print("dismisses form")
                self.presentationMode.wrappedValue.dismiss()
            }) {
                Text("Dismiss")
            }.padding(.bottom, 50)
            Text("This is a modal")
        }
    }
}

设置断点后,每次都会调用print(“ Button Pushed”),但不会调用.sheet的ModalView,自然也不会调用ModalView类的主体。

swiftui xcode11
1个回答
0
投票

我认为问题是您的.sheet不在List本身上,而是在导致错误的代码中的Button上。

尝试以下方法:

struct ContentView: View {
    @State var show_modal = false
    var body: some View {
        List {
            Button(action: {
                print("Button Pushed")
                self.show_modal = true
            }) {
                Text("Show Modal")
            }
        }.sheet(isPresented: self.$show_modal, onDismiss: {
            print("dismiss")
        }) {
            ModalView()
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.