I'm dealing with a very strange issue in SwiftUI. Basically, I'm trying to have a list of subviews (Collapsible()
, in the code below), where each of these views can expand and collapse when tapped. Additionally, these views display one HStack
for every item
in the items
state variable, and there's a button to add one additional item per tap. Each Collaspible()
looks like this:
Now, I want to display these Collapsibles in a list. In the code below, I've just added three in a pretty straightforward manner:
struct ContentView: View {
var body: some View {
List {
Collapsible()
Collapsible()
Collapsible()
}
}
}
That ends up looking like this:
Here's where the issue comes in. If I expand one of these collapsibles and add some items, this is what happens:
The list delegates extra room for the Collapsible()
, even though when it is not expanded, the maxHeight
is 0. Does anyone know why this is happening and how to avoid it?
Here's the code for the Collapsible()
struct.
struct Collapsible: View {
@State private var isExpanded: Bool = false
@State private var items: [String] = ["item1", "item2", "item3"]
var body: some View {
VStack {
HStack {
Text("Tap Me")
Spacer()
Text("Info")
}
.contentShape(Rectangle())
.onTapGesture {
isExpanded.toggle()
}
VStack {
ForEach(items, id: \.self) { item in
HStack {
Text("Item")
Spacer()
Text("Info")
}
.padding(.vertical, 5)
}
Button("Add Item") {
items.append("new item")
}
}
.frame(maxHeight: isExpanded ? .none : 0)
.clipped()
}
.background(Color.cyan)
}
}