1
votes

I would like to have a splitview with items in the detail view beeing double tappable. I created the following example to showcase my problem:

struct ContentView: View {
var body: some View {
    NavigationView {
        List(["Hello", "World"]) { str in
            NavigationLink(destination: DetailView(title: str)) {
                Text(str)
            }
        }
    }.frame(minWidth: 300, minHeight: 300)
  }
}

struct DetailView: View {

    let title: String
    @State var isShowingAlert = false

    var body: some View {
        VStack {
            Text(title)
            List(["This", "is", "SwiftUI", "!"]) { str in
                Text(str).onTapGesture(count: 2) {
                self.isShowingAlert = true
            }.alert(isPresented: self.$isShowingAlert) { () -> Alert in
                Alert(title: Text(str), message: Text("This is a hello message"), dismissButton: Alert.Button.default(Text("Ok")))
            }
        }
    }.frame(minWidth: 200)
  }
}

So The splitview part works as expected. But when I double tap on a row item, it always shows me the alert twice with the content below. So it does not matter which item I tap. It always shows me the first and second item in the alert. After dismissing the first alert with title "This", the second is shown with title "is":

The first alert: The first alert shown after tapping any item in the list

The second alert: The second alert shown after dismissing the first alert

Why does it show two alerts with one double tap? And Why always the first two items even if I select the last item in the list? Any suggestions or solutions? Thank you very much :)

1

1 Answers

1
votes

You create many alerts by attaching one to every list row and activate all of them by switching one state... consequences actually unpredictable.

Instead it should be only one alert managed by own state. So here is possible solution:

struct DetailView: View {

    let title: String
    @State private var selectedItem: String = ""
    @State private var isShowingAlert = false

    var body: some View {
        VStack {
            Text(title)
            List(["This", "is", "SwiftUI", "!"]) { str in
                Text(str).onTapGesture(count: 2) {
                    self.selectedItem = str        // << store clicked raw item
                    self.isShowingAlert = true     // << activate alert !!
                }
            }
            .alert(isPresented: self.$isShowingAlert) { // << attach here !!
                Alert(title: Text(self.selectedItem), message: Text("This is a hello message"), dismissButton: Alert.Button.default(Text("Ok")))
            }
        }.frame(minWidth: 200)
    }
}