Reputation: 1604
Okay so I'm trying to change the opacity on the selected image. This is how my code looks like
struct TestView: View {
@State var opacity: CGFloat = 0.5
let columns = [GridItem(.flexible(), spacing: 1), GridItem(.flexible(), spacing: 1), GridItem(.flexible(), spacing: 1)]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 1) {
ForEach(0..<90, id: \.self) { _ in
Image("placeholder")
.resizable()
.scaledToFill()
.clipped()
.opacity(opacity)
.onTapGesture {
opacity = 1
}
}
}
}
}
}
However this is changing all the images back to 1 instead of the selected image. How would I be able to get this to work.
Upvotes: 1
Views: 1026
Reputation: 1000
The problem is you're not identifying which image is selected. Instead when you tap the image it just sets the current opacity for all the views to 1.
@State var selectedItem: Int? = nil
let columns = [GridItem(.flexible(), spacing: 1), GridItem(.flexible(), spacing: 1), GridItem(.flexible(), spacing: 1)]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 1) {
ForEach(0..<90, id: \.self) { row in
Image("placeholder")
.resizable()
.scaledToFill()
.clipped()
.opacity(selectedItem == row ? 0.5 : 1) // Change opacity based on selection
.onTapGesture {
// Set the selected row when the image is tapped.
selectedItem = row
}
}
}
}
}
This code sets the selectedItem
state var when the image is tapped. Then it checks if the current image is the selected image. If it is, then it sets the opacity to 0.5, if not it sets it to 1.
Upvotes: 3