swiftui foreach 中 展开收缩自定义界面
时间: 2023-07-15 08:10:43 浏览: 57
你可以使用 `@State` 属性来控制展开和收缩的状态,并在 `ForEach` 中使用条件语句来显示或隐藏自定义界面。以下是一个简单的示例代码:
```
struct ContentView: View {
@State var isExpanded = false
var body: some View {
VStack {
Button(action: {
self.isExpanded.toggle()
}) {
Text(isExpanded ? "收起" : "展开")
}
if isExpanded {
ForEach(0..<5) { index in
CustomView(index: index)
}
}
}
}
}
struct CustomView: View {
var index: Int
var body: some View {
Text("Custom View \(index)")
}
}
```
在上面的示例中,我们首先创建了一个 `isExpanded` 的 `@State` 属性来控制展开和收缩的状态。然后我们创建了一个 `Button` 来切换状态。
在 `ForEach` 中,我们使用了一个条件语句来检查当前是否展开。如果展开,我们就使用 `CustomView` 来显示自定义视图。否则,我们不显示任何内容。
你可以根据自己的需求来自定义 `CustomView`。