ios – ScrollViewReader ScrollTo notWorking

I’m creating a horizontal menu and I’m using horizontal ScrollView and an HStack to view its items. Everything seems to work but I have a problem with ScrollViewReader.. As you should from the code when currentIndex changes I pass its value to the proxy.scrollTo() method but I don’t get any results, the ScrollView does not follow the modification of currentIndex remaining still in its original position. Can you tell me where I’m going wrong? thank you all

struct ScrollableTabMenu<T:CaseIterable & Hashable & Identifiable>: View  {
    var items: [T]
    var title: KeyPath<T, String>
    @Binding var currentIndex: Int
    @Namespace private var animation
    var body: some View {
        ScrollView(.horizontal) {
            ScrollViewReader { proxy in
                HStack {
                    ForEach(items) { screen in
                        let index = items.firstIndex(of: screen)!
                        Button {
                            currentIndex = index
                        } label: {
                            Text(screen[keyPath: title])
                                .overlay(alignment: .bottom){
                                    if currentIndex == index  {
                                        RoundedRectangle(cornerRadius: 6)
                                            .frame(height: 1)
                                            .matchedGeometryEffect(id: "AninamtionTAB", in: animation)
                .onChange(of: currentIndex, { _, newValue in
                    withAnimation {
                        proxy.scrollTo(newValue, anchor: .leading)
        .contentMargins(.horizontal, 16)

Latest articles


Related articles

Leave a reply

Please enter your comment!
Please enter your name here