Reputation: 63
I added three buttons inside the scroll view and I want to get the effect when a user clicks a button - that only that button is clicked and not every one of the buttons, so that the hidden description appears only on the clicked button.
And code:
struct WordCells: View {
@State private var toggleView = false
var numberOfItems = Int.init()
var body: some View {
GeometryReader { geometry in
VStack(spacing: 40.0) {
ForEach(0..<self.numberOfItems) {item in
Button(action: {
withAnimation(.easeInOut(duration: 0.5)) {
self.toggleView.toggle()
}
})
{
VStack {
HStack {
Text("Button Text")
.fontWeight(.bold)
.foregroundColor(.black)
.font(.callout)
Spacer()
Text("Description")
.fontWeight(.bold)
.foregroundColor(.customLabel)
.font(.callout)
}
if self.toggleView {
HiddenDescriptionView()
}
}
.frame(width: geometry.size.width/1.3)
}
.padding(23.0)
.background(Color.white)
}
.clipShape(RoundedRectangle(cornerRadius: 32))
.shadow(color: .customLabel, radius: 15)
}
}
}
}
Upvotes: 2
Views: 538
Reputation: 257493
Here is a solution. Tested with Xcode 11.4 / iOS 13.4
struct WordCells: View {
@State private var toggleView: Int? = nil // << selection
var numberOfItems = Int.init()
var body: some View {
GeometryReader { geometry in
VStack(spacing: 40.0) {
ForEach(0..<self.numberOfItems) {item in
Button(action: {
withAnimation(.easeInOut(duration: 0.5)) {
if self.toggleView == item { // << here !!
self.toggleView = nil
} else {
self.toggleView = item
}
}
})
{
VStack {
HStack {
Text("Button Text")
.fontWeight(.bold)
.foregroundColor(.black)
.font(.callout)
Spacer()
Text("Description")
.fontWeight(.bold)
.foregroundColor(.gray)
.font(.callout)
}
if self.toggleView == item { // << selection !!
HiddenDescriptionView()
}
}
.frame(width: geometry.size.width/1.3)
}
.padding(23.0)
.background(Color.white)
}
.clipShape(RoundedRectangle(cornerRadius: 32))
.shadow(color: .gray, radius: 15)
}
}
}
}
Upvotes: 1