swiftUI PresentaionLink 第二次不起作用

swiftUI PresentaionLink does not work second time

我有一个用swiftUI写的ContentView,简单如下。

var body: some View {
    
    NavigationView {
        List {
            Section {
                PresentationLink(destination: Text("new Profile")) {
                    Text("new Profile")
                }
            }
        }
    }

我第一次点击新配置文件时一切正常,但是当我关闭模式并尝试再次点击时,它不起作用。

这是错误还是功能?

PresentationLink 已在 Xcode 11 beta 4 中弃用,取而代之的是 .sheet,这似乎可以解决问题。

Added improved presentation modifiers: sheet(isPresented:onDismiss:content:), actionSheet(isPresented:content:), and alert(isPresented:content:) — along with isPresented in the environment — replace the existing presentation(_:), Sheet, Modal, and PresentationLink types. (52075730)

如果您将代码更改为 .sheet,如下所示:

import SwiftUI

struct Testing : View {
    @State var isPresented = false

    var body: some View {
        NavigationView {
            List {
                Button(action: { self.isPresented.toggle() })
                    { Text("Source View") }
                }
            }.sheet(isPresented: $isPresented, content: { Text("Destination View") })
    }
}

然后您将可以根据需要多次使用模态框,而不仅仅是一次。

编辑:在实际场景中实现后,我发现如果将 .sheet 放在 List 中,潜在的错误似乎仍然存在。如果您遵循上面的代码示例,您将不会遇到此问题,但在您使用 List 的真实场景中,您可能需要有关已选择的特定项目的信息传递给模态。在这种情况下,您将需要通过 @State var 或其他方式传递有关选择的信息。下面是一个例子:

import SwiftUI

struct Testing : View {
    @State var isPresented = false
    @State var whichPresented = -1

    var body: some View {
        NavigationView {
            List {
                ForEach(0 ..< 10) { i in
                    Button(action: {
                            self.whichPresented = i
                            self.isPresented.toggle()
                })
                        { Text("Button \(i)") }
                    }
                }
            }.sheet(isPresented: $isPresented, content: { Text("Destination View \(self.whichPresented)") })
    }
}