'Make List Sections non-collapsible in SwiftUI when embedded into a NavigationView SwiftUI
When I embed a List
grouped into Section
s into a NavigationView
the section headers become collapsible. I'd like to keep them non-collapsible, just like when the List
is not embedded into the NavigationView
.
My current code (with the NavigationView):
import SwiftUI
struct MyGroup {
var name:String, items:[String]
}
struct ContentView: View {
var groups : [MyGroup] = [
.init(name: "Animals", items: ["🐕","🐩","🐂","🐄","🐈","🦩","🐿","🐇"]),
.init(name: "Vehicles", items: ["🚕","🚗","🚃","🚂","🚟","🚤","🛥","⛵️"])]
var body: some View {
NavigationView {
VStack {
List {
ForEach(groups, id: \.self.name) { group in
Section(header: Text(group.name)) {
ForEach(group.items, id:\.self) { item in
Text(item)
}
}
}
}
}.navigationTitle("collections")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Solution 1:[1]
It is default style applied, you can make it explicitly set for List
like below (tested with Xcode 12 / iOS 14)
List {
ForEach(groups, id: \.self.name) { group in
Section(header: Text(group.name)) {
ForEach(group.items, id:\.self) { item in
Text(item)
}
}
}
}.listStyle(InsetGroupedListStyle()) // or GroupedListStyle
Solution 2:[2]
In case you're stumbling on this... The issue doesn't have anything to do with being embedded in a NavigationView as the OP and @Danial mentioned. It's because it's embedded in the the VStack at the first level of the NavigationView in the example code. Seems like a SwiftUI bug to me.
Solution 3:[3]
Just using the SidebarListStyle in listStyle modifier
.listStyle(SidebarListStyle())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Andrew B |
Solution 3 | Milad |