从列表中消除SwiftUI模态“工作表”

时间:2019-09-05 09:50:33

标签: swiftui

我正在尝试在列表中展示一个模式。测试版中的模式已进行了很多次更改,但是我相信我使用的是正确/最新的方式(自Xcode Beta 7起)。但是,当我从列表中触发模式时,对于每个列表项,它都会打开一次,但是再也不会打开。

import SwiftUI

//This works perfectly fine

struct BasicTest : View {

struct SampleObject: Identifiable {
    var id = UUID()
    var name: String
}

let sampleObjects = [
        SampleObject(name: "Buffalo"),
        SampleObject(name: "Italy"),
        SampleObject(name: "Portland"),
    ]
@State private var showModal:Bool = false

var body: some View {

    Button(action: {
        print("Modal to open")
        self.showModal = true

    }) {
        Text("Show Modal")

    }.sheet(isPresented: self.$showModal)
        {
            TestDetailView(name: "Example")
        }
    }
}

#if DEBUG
struct BasicTest_Previews: PreviewProvider {
    static var previews: some View {
        BasicTest()
        }
}
#endif

//this one only opens once
struct ListTest : View {

    struct SampleObject: Identifiable {
        var id = UUID()
        var name: String
    }

    let sampleObjects = [
            SampleObject(name: "Buffalo"),
            SampleObject(name: "Italy"),
            SampleObject(name: "Portland"),
        ]
    @State private var showModal:Bool = false

    var body: some View {
            List {
                ForEach(sampleObjects) {
                    item in
                    Button(action: {
                        print("Modal to open")
                        self.showModal = true

                    }) {
                        Text("Show Modal for \(item.name)")

                    }.sheet(isPresented: self.$showModal)
                        {
                            TestDetailView(name: item.name)
                        }
                    }
                }
            }
        }

#if DEBUG
struct ListTest_Previews: PreviewProvider {
    static var previews: some View {
        ListTest()
        }
}
#endif

struct TestDetailView: View {

    @Environment(\.presentationMode) var presentationMode
    var name: String

    var body: some View {
        VStack {
            Button(action: {
                print("Button clicked")
                self.presentationMode.wrappedValue.dismiss()
                }) {
                    Image(systemName: "chevron.compact.down").font(Font.system(.largeTitle).bold())
                }
            Text(name)
        }
    }
}







我看不到任何错误消息,只是试图再次打开时闪烁。

1 个答案:

答案 0 :(得分:0)

如果您为列表行创建视图并将.sheet()移到其中,它将起作用