Reputation: 4330
I'm trying to optimize the layout of a Detail view for iPad in a SwiftUI NavigationSplitView. I crafted the Detail view to show an Image at the top, then each attribute of a data model in a Section with a header. That all works, but when I attempt to put the image and a few of the attributes in an HStack so they are side by side (in an iPad) I lose all of the Section formatting. The data still exists, just not formatted as sections. I've tried many combinations of surrounding containers - VStack, Form, List, Group, another Section but nothing works. I have not been able to find any literature that says what I am trying will not work.
Here's a simplified version. This example does not even use the NavigationSplitView - and it still breaks.
struct ContentView: View {
let thingOne = Thing(name: "One", source: "Source One", category: "Category One", owner: "Owner One")
var body: some View {
List {
//1
//HStack { uncomment this and the formatting breaks
Group1()
Group2(thing: thingOne)
//}
Group3(thing: thingOne)
}
.listStyle(PlainListStyle())
.padding()
}//body
struct Group1: View {
var body: some View {
Image(systemName: "gear")
.resizable()
.frame(width: 150, height: 150)
}
}//group 1
struct Group2: View {
var thing: Thing
var body: some View {
Section {
Text(thing.name)
} header: {
Text("Thing Name:")
}//section
Section {
Text(thing.source)
} header: {
Text("Thing Source:")
}//section
}
}//group 2
struct Group3: View {
var thing: Thing
var body: some View {
Section {
Text(thing.category)
} header: {
Text("Thing Cateogry:")
}//section
Section {
Text(thing.owner)
} header: {
Text("Thing Owner:")
}//section
}
}//group 3
}//content view
struct Thing: Identifiable, Hashable {
let id = UUID()
let name: String
let source: String
let category: String
let owner: String
}//struct thing
Comment out the HStack at //1:
Uncomment HStack at //1:
Any guidance would be appreciated. Xcode 14 beta 6, iOS 16
Upvotes: 2
Views: 1747
Reputation: 212
According to the SwiftUI doc, you're advised to use Sections inside supported parent views such as List, Picker, and Form. (Use Section instances in views like List, Picker, and Form to organize content into separate sections.)
The issue is that you're trying to divide unsupported views into sections. Native containers such as Sections sometimes have strict constraints to allow a more consistent design system.
Try putting sections inside a List, and it should work as you've desired, although in this case I would build a custom section view.
struct Group2: View {
var thing: Thing
var body: some View {
HStack {
// Assuming you want to put two Sections horizontally (which is not the best usage of SwiftUI native sections)
// You can put two separate Lists inside HStack, and a section in each List.
List {
Section {
Text(thing.name)
} header: {
Text("Thing Name:")
}//section
}
List {
Section {
Text(thing.name)
} header: {
Text("Thing Name:")
}//section
}
}
}
}//group 2
Upvotes: 1