Home > other >  SwiftUI Can't Put Sections Inside Other Containers
SwiftUI Can't Put Sections Inside Other Containers

Time:09-01

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:

enter image description here

Uncomment HStack at //1:

enter image description here

Any guidance would be appreciated. Xcode 14 beta 6, iOS 16

CodePudding user response:

According to the SwiftUI doc, you're advised to use Sections inside supported parent views such as List, Picker, and Form. (iPhone iPad

  • Related