ScrollView breaks .sheet representation

2019-08-24 06:01发布

问题:

I am trying to get a sheet representation work nested in multiple views inside a ScrollView.

Without the ScrollView the .sheet modifier works fine, but when I wrap everything inside the scroll view the modifier, triggers only once. So on the first tap the sheet appears fine, but after dismissing it I can not trigger it again. I am unsure whether this is a bug in SwiftUI itself or if I am doing something here.

Note: If I add the .sheet modifier to the ScrollView itself, everything is working. But for my use case the .sheet modifier is added deeply nested inside a custom view inside the ScrollView.

I am using the Xcode Beta 5

Without ScrollView - Works

struct SheetWorks: View {
    @State var showSheet = false

    var strings = [
      "Hello", "World", "!"
    ]

    var body: some View {
        HStack {
            ForEach(strings) { string in
                Button(action: {self.showSheet.toggle()}) {
                    Text(string)
                }
                .sheet(isPresented: self.$showSheet) {
                    Text("Here is the sheet")
                }
            }
        }
        .padding()
    }
}

With ScrollView - Does not work

struct SheetDoesntWork: View {
    @State var showSheet = false

    var strings = [
      "Hello", "World", "!"
    ]

    var body: some View {
        ScrollView(.horizontal) {
            HStack {
                ForEach(strings) { string in
                    Button(action: {self.showSheet.toggle()}) {
                        Text(string)
                    }
                    .sheet(isPresented: self.$showSheet) {
                        Text("Here is the sheet")
                    }
                }
            }
            .padding()
        }
    }
}

Maybe someone has experienced something similar or can point me in the right direction. I really appreciate any help.

Edit: This problem still persists in Beta 6

回答1:

Take a look at my answer here: https://stackoverflow.com/a/57259687/554203

Basically you should use just one .sheet outside the loop and dynamically open the desired view based on a local var.

var covers = coverData
var selectedTag = 0

Group {
   ForEach(covers) { item in
      Button(action: { 
         self.selectedTag = item.tag
         self.isPresented.toggle() 
      }) {
        CoverAttributes(
           title: item.title,
           alternativeTitle: alternativeTitle,
           tapForMore: item.tapForMore,
           color: item.color,
           shadowColor: item.shadowColor)
      }
   }
}
.sheet(isPresented: self.$isPresented, content: { 
    Text("Destination View \(self.selectedTag)") 
    // Here you could use a switch statement on selectedTag if you want
})


标签: swiftui