List view being pushed down as I push to another view

  Kiến thức lập trình

I’m working in this search view using swiftUI to build it. There’s a List in my view being populated by a for each, each rows takes the user to another view. But when I push another view, the back button from the navigation bar of the new view pushes the whole view down. creating a weird effect, that gives the impression of you clicking the wrong cell. Here Is the code:

struct SearchView: View {
    @Binding var isSearching : Bool
    @FocusState var isFocused : Bool
    @StateObject var viewModel = SearchVM()
    var body: some View {
        VStack{
            HStack{
                VStack{
                    HStack{
                        Image(systemName: "magnifyingglass")
                            .foregroundStyle(Color.secondaryColor)
                        TextField("Pesquisar...", text: $viewModel.searchText )
                            .focused($isFocused)
                    }.modifier(OutlinedCardStyle(padding: 12))
                    
                }
                .textFont(style: .montserrat14)
                
                
                Button(action: {
                    withAnimation(.easeOut(duration: 0.4)) {
                        isSearching.toggle()
                        isFocused = isSearching
                    }
                }, label: {
                    Text("Cancelar")
                        .bold()
                }).padding(.leading,5)
            }.padding([.horizontal,.top])
            List {
                ForEach($viewModel.matchedSections, id: .id) { $section in
                    Section($section.sectionName.wrappedValue){
                        ForEach($section.subSections, id: .id){ subsection in
                            NavigationLink{
                                AppointmentView()
                            }label:{
                                Text(subsection.sectionName.wrappedValue)
                            }
                            
                        }
                    }
                }
               
            } .listStyle(.plain)
                .animation(.smooth, value: viewModel.matchedSections)
                
            
            Spacer()
        }
        .onAppear{
            isFocused = isSearching
        }
    }
}

I tried to embend the view in a scroll view to see if there’s was something related, as something similar already happened and doing this worked. However this made the list simply disappear. Searching I found that this is the normal behavior when trying to put a list inside a scroll view.

I removed the list and left only the forEach, and the navigation worked fine. So the problem is really in the list. Is there a way to work around this? I’d really like to still use the native list since creating the sections its easier.

LEAVE A COMMENT