3

I'm able to scroll to a vertical List item using ScrollViewReader proxy.

I tried doing something similar with Horizontal list, but it totally messed up the view.

Any suggestion, how this can be done ?

tia!

   ScrollViewReader { proxy in
        ScrollView(.horizontal, showsIndicators:false) {
            ForEach(0..<items.count) { index in
                Text(items[index].title)
                    .id(index)
                    .onTapGesture {
                        print("tapped \(index)")
                    }
            }
            .onAppear{
                proxy.scrollTo(selectedIndex, anchor: .center)
            }
        }
    }
1

1 Answer 1

4

ScrollView will not layout your views in a row just because you've specified .horizontal scrolling.

You need to specify HStack/LazyHStack explicitly inside ScrollView.

Another problem you may have encountered is that the scrolling position is not accurate, this can be fixed with DispatchQueue.main.async:

ScrollViewReader { proxy in
    ScrollView(.horizontal, showsIndicators: false) {
        HStack { // or LazyHStack
            ForEach(0..<items.count) { index in
                Text(items[index].title)
                    .id(index)
                    .onTapGesture {
                        print("tapped \(index)")
                    }
            }
        }
        .onAppear {
            DispatchQueue.main.async { 
                proxy.scrollTo(selectedIndex, anchor: .center)
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer @Phil Dukhov. This works for me. Especially ``` DispatchQueue.main.async {}``` block did the work. For others help: In my case, I was navigating from one View to another (SwiftUI) and in the onAppear block, I was trying to scroll to the selected item. Just adding the above line works for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.