Reputation: 389
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)
}
}
}
Upvotes: 3
Views: 2153
Reputation: 88182
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)
}
}
}
}
Upvotes: 4