OUTLINE
I have 2 views, the first (view1) contains a HStack
and an @ObservableObject
. When the user selects a row from the HStack
the @ObservableObject
is updated to the string name of the row selected.
In view2 I have the same HStack
as the first HStack
in view1. This HStack
observes @ObservableObject
and desaturates all other rows except the one that matches the @ObservableObject
.
PROBLEM
The HStack
list in view2 is wider than the page so I would like to automatically scroll to the saturated/selected row when the view appears. I'm not totally sure how to use ScrollTo
as it needs an integer and I am only storing/observing the string name.
VIEW 1
class selectedApplication: ObservableObject {
@Published var selectedApplication = "application1"
}
struct view1: View {
@ObservedObject var selectedOption = selectedApplication()
var applications = ["application1", "application2", "application3", "application4", "application5", "application6", "application7", "application8", "application9", "application10"]
var body: some View {
VStack{
ScrollView(.horizontal){
HStack{
ForEach(applications, id: \.self) { item in
Button(action: {
self.selectedOption.selectedApplication = item
}) {
VStack(alignment: .center){
Text(item)
}
}
}
}
}
}
}
}
View2:
struct View2: View {
@ObservedObject var application: selectedApplication
var applications = ["application1", "application2", "application3", "application4", "application5", "application6", "application7", "application8", "application9", "application10"]
var body: some View {
HStack{
ScrollView(.horizontal, showsIndicators: false) {
ScrollViewReader{ scroll in
HStack{
ForEach(applications, id: \.self) { item in
Button(action: {
application.selectedApplication = item
}) {
Text(item)
.saturation(application.selectedApplication == item ? 1.0 : 0.05)
}
}
}
}
}
}
}
}