我在滚动视图里面添加了三个按钮,我想在用户点击按钮的时候得到这样的效果--只有这个按钮被点击,而不是每个按钮都被点击,这样隐藏的描述只出现在被点击的按钮上。
还有代码。
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)
}
}
}
}
这里有一个解决方案。用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)
}
}
}
}