So let’s say for example that I have a list declared like this
List {
Section {
Text(“Test Row Title 1”)
}
Section {
Text(“Test Row Title 2”)
}
}
Is it possible to make the style of that the same as UITableView.Style.insetGrouped? I can’t find any information about that.
I thought that it would be as simple as .listStyle(InsetGroupedStyle())
SwiftUI's List views have a listStyle() modifier to control how the list looks, and there are two options you're likely to want: . grouped (or GroupedListStyle() for Xcode 12) to get the old-style grouping of items, and . insetGrouped (or InsetGroupedListStyle() for Xcode 12) to get the newer style grouping of items.
In SwiftUI we organize all our UI using those 3 stacks. We also use Group , a view that, similarly to stacks, can be used to group together multiple views, but contrary to stack views, it does not affect layout. VStack { Group { Text("Hello World") Text("Hello again!") } }
Apparently there is a new API in iOS/iPadOS 14 which finally allows InsetGrouped style to be in SwiftUI.
List {
...
}
.listStyle(InsetGroupedListStyle())
In iOS 13.2, you can set .environment(\.horizontalSizeClass, .regular)
on .listStyle(GroupedListStyle())
to get the same style as UITableView.Style.insetGrouped
.
List {
Section {
Text(“Test Row Title 1”)
}
Section {
Text(“Test Row Title 2”)
}
}.listStyle(GroupedListStyle())
.environment(\.horizontalSizeClass, .regular)
https://sarunw.com/tips/inset-grouped-in-swiftui/
You can add .environment(\.horizontalSizeClass, .regular)
to your list.
My implementation is not ideal, but this is what I'm happy with for now. I stared by creating a ViewModifier, CardViewModifier() that I use for creating an inset card view. I use it in several places in my App, not just with the lists.
struct CardViewModifier: ViewModifier {
var backgroundColor = Color(.systemBackground)
func body(content: Content) -> some View {
content
.padding()
.frame(maxWidth: .infinity)
.background(Color(.systemBackground))
.cornerRadius(12)
.padding()
}
}
To "fake" an insetGrouped List, I convert the List to a ScrollView and the Sections to VStacks, like so.
struct ContentView: View {
let data = ["Row 1", "Row 2", "Row 3", "Row 4", "Row 5"]
var body: some View {
ScrollView {
VStack {
ForEach(data, id:\.self) { row in
VStack {
Text("Section 1, \(row)")
Divider()
}
}
}
.modifier(CardViewModifier())
VStack {
ForEach(data, id:\.self) { row in
Text("Section 2, \(row)").padding()
}
}
.modifier(CardViewModifier())
}
.background(Color(.secondarySystemBackground))
}
}
Like I said its not ideal, but it will work until Apple (or someone else) creates an InsetGroupedListStyle. When that happens, it should be a simple case of changing the ScrollView back to a List and the VStacks back to Sections.
Good luck...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With