SwiftUI关闭.alert时弹出NavigationView。

3
我已经在watchos 8+上运行了以下示例代码:
struct TestView: View {
  @State private var showingAlert = false
  
  var body: some View {
    NavigationView {
      NavigationLink {
        
        Button(action: {
          showingAlert = true
        }, label: {
          Text("Show dialog")
        })
        .alert("", isPresented: $showingAlert, actions: {
          Button("refresh") {
          }
        })
        
      } label: {
        Text("Show detail")
      }
    }
  }
}

这是一个简单的屏幕,带有导航链接,可以推出一个带有简单按钮的新视图。 当按钮按下时,我会显示一个带有简单按钮的警报。当警报被解除时,详细视图也被解除,界面返回到其原始状态。

它看起来像这样:

enter image description here

我想知道我错过了什么。我如何关闭警告框,但仍停留在显示“显示对话框”按钮的第二个视图上。

你尝试创建第二个视图来显示详情了吗?这样做的好处是,弹出的警告框不会影响导航链接的显示。 - Ptit Xav
1个回答

0

查看分离以及不必要的NavigationView(仅适用于watchOS!)。

以下是修复后的代码。已在Xcode 13.4 / watchOS 8.5中测试通过。

demo

struct TestView: View {
  var body: some View {
      NavigationLink {
        DestinationView()
      } label: {
        Text("Show detail")
      }
  }

  struct DestinationView: View {
    @State private var showingAlert = false
    var body: some View {
        Button(action: {
          showingAlert = true
        }, label: {
          Text("Show dialog")
        })
        .alert("", isPresented: $showingAlert, actions: {
          Button("refresh") {
          }
        })
    }
  }
}

已确认为有效的解决方法。 - Laufwunder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接