Home > database >  SwiftUI List scrolls to the top on tapping to view sheet
SwiftUI List scrolls to the top on tapping to view sheet

Time:02-17

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)}
}

CodePudding user response:

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.

  • Related