在 SwiftUI Picker 列表中使用 headers 部分?

Use section headers on SwiftUI Picker list?

我正在尝试使用 SwiftUI 和 Picker() 获得类似于以下内容的内容

但是当我尝试使用 Section(header: ) 时,我得到以下信息:

Form {
    Picker("S", selection: $sensor) {
        Section(header: Text("This should be a header")) {
           Text("This is the content")
            Text("This is more content")
        }
        
        Section(header: Text("Another header")) {
           Text("This is the content 2")
            Text("This is more content 2")
        }
    }
}

我不认为那是一个 Picker。我认为这是两个可能只有一个选择变量的选择器。

在 Xcode 13 中,您可以使用内联选择器样式来创建嵌入外观

import SwiftUI
struct PickerModel: Identifiable{
    let id: UUID = UUID()
    var parent: String
    var children: [String]
}

var pickers: [PickerModel]{
    [PickerModel(parent: "Child 1-B", children: ["Child 1-A","Child 1-B","Child 1-C"]),
     PickerModel(parent: "Parent 2", children: ["Child 1-A","Child 1-B","Child 1-C","Child 1-D"])
    ]
}
struct MultiplePickerView: View {
    @State var sensor: String = "no sensor selected"
    var body: some View {
        Form{
            Text(sensor)
            ForEach(pickers){picker in
                Section(header: Text(picker.parent)){
                    Picker("", selection: $sensor){
                        ForEach(picker.children, id:\.description){child in
                            Text(child)
                                //Make sure tag is unique across pickers
                                .tag("\(picker.parent)  \(child)")
                        }
                    }.pickerStyle(InlinePickerStyle())
                        .labelsHidden()
                }
            }
        }
    }
}

但在 Xcode 12 中,您必须手动创建选择器功能

struct MultiplePickerView: View {
    @State var sensor: String = "no sensor selected"
    var body: some View {
        Form{
            Text(sensor)
            ForEach(pickers){picker in
                Section(header: Text(picker.parent)){
                        ForEach(picker.children, id:\.description){child in
                            //tag must be unique throughout the pickers
                            let tag = "\(picker.parent)  \(child)"
                            HStack{
                                Text(child)
                                Spacer()
                                
                                if sensor == tag{
                                    Image(systemName: "checkmark").foregroundColor(.blue)
                                }
                            }
                            .contentShape(Rectangle())
                            .onTapGesture {
                                sensor = tag
                            }
                            
                        }
                }
            }
        }
    }
}