0
votes

I have a ScrollView with a ForEach. When an item is at the top of the scroll view I would like to dynamically change the header at the top of the list to that items name. I tried an onAppear but that just sets the header title to the first item in the array.

'''

struct RestaurantItemList: View {
            
@State var headerTitle = "Initial Value"
            
var body: some View {
    VStack{
        Text(headerTitle)
        ScrollView{
            ForEach(myFoodVM.restaurantsMenu, id:\.self){item in
                HStack{
                    NavigationLink(destination: ConsumableDetailView(item: item)){
                        ConsumableRowWithPicture(consumable: item)
                        .onAppear(){
                           self.headerTitle = item.name
                                   }
                              }
                          }
                      }
                }
            }
        }
    }
    

'''

There doesn't seem to be any way to access the current top item in the scrollView. Does anyone have a way to access that item dynamically?

Better fit for UIKit or maybe SwiftUI Introspect. There isn’t a native SwiftUI function for this.jnpdx