I created a vertical scrollview as below:
struct UserFeedView: View {
var body: some View {
@State var selectedFilter: Filter?
let filters = [
Filter(name: "All"),
Filter(name: "fil1"),
Filter(name: "fil2"),
Filter(name: "fil3"),
]
VStack() {
ScrollView(.horizontal,showsIndicators: false) {
HStack(spacing: 15) {
ForEach(filters) { filter in
Text(filter.name)
.font(.system(size: selectedFilter?.id == filter.id ? 30 : 20))
.onTapGesture {
selectedFilter = filter
}
}
}
.padding(.top, 10)
.padding(.leading, 30)
}
.frame(height: 150)
.onAppear {
if let first = filters.first {
selectedFilter = first
}
}
Spacer()
}
}
}
I am trying to change the font size of the selected item so the user can see what has been selected.
The goal is to :
When the user first access the screen, the first item is selected then when scrolling and selecting an item, the selected item has an increased size and bold compared to the other item.
Any idea?
thanks
2
Answers
Assuming
Filter
isIdentifiable
:You can add a
@State
to your view that indicates which filter is selected.Then it is just a matter of showing different views depending on whether the filter is the selected one:
You can extract the common
onTapGesture
by adding aGroup
:You could try something simple like this:
In this example code, tapping on a
Filter
name in the scrollview, increases thefont size of the tapped
Filter
to 30, leaving the other entries of size 20.The code also shows, that the first
Filter
is selected(font size 30) when the view first appear.
EDIT-1
added
.bold(selected?.id == filter.id)
to have a bold appearance as well when selected.