1

I have a List in my View that has an onTapGesture on each of the items in the list that is set to display a sheet of a separate View and passes selected object into it to display more information.

The information gets passed in but every time I tap on an item in the list it will display the sheet but scroll all the way back to the top of the List, does anyone know if there's a fix for this or if its just a bug?

Code Below:

@State var selectedItem: Item = Item()
@State var showPopup = false

var body: some View {

  VStack{
            List(items, id: \.self) {item in
                ItemCard(Item: item)
                    .contentShape(Rectangle())
                    .onTapGesture(){
                        self.selectedItem = item
                        self.showPopup = true
                    }
            }.id(UUID())
        }.sheet(isPresented: $showPopup) {ItemDetails(i:selectedItem)}
}
A-Fairooz
  • 410
  • 3
  • 11
  • 3
    Unrelated to your issue, but I'd suggest you look into `sheet(item:)` rather than `sheet(isPresented:)` -- the latter tends to have issues with displaying the last selected item sometimes. The former will guarantee the sheet information is up-to-date. See https://stackoverflow.com/questions/66162219/swiftui-switch-sheet-on-enum-does-not-work/66162319#66162319 for example – jnpdx Feb 16 '22 at 16:53

1 Answers1

4

When you assign a new id to your List on every single render (like you do when you do .id(UUID())), SwiftUI considers it a completely new View. So, when you change your @State by tapping an item, SwiftUI thinks a new List is created and scrolls to the top.

Remove .id(UUID()) to fix this.

jnpdx
  • 45,847
  • 6
  • 64
  • 94