I'm using DisclosureGroups to display a hierarchy in outline form, and added code to make the lines selectable. This works, except that the root entry cannot be selected. The root and branch lines can be expanded as expected, and all lines other than the root line can be selected.
I'm developing this as a MacOS application, but running it in the iPhone simulator revealed another odd behavior. When the "Root" line is clicked (anywhere within the line), its disclosure state is toggled. When other lines are clicked, only their disclosure triangles alter their disclosure state.
@main struct DisclosureApp: App {
@State var selection: UUID?
var root = OutlineNode.newOutline()
var body: some Scene {
WindowGroup {
List(selection: $selection)
{
OutlineView(node: root)
}
}
}
}
struct OutlineView: View
{
let node: OutlineNode
@State var isExpanded: Bool = true
var body: some View {
if node.children.isEmpty {
Text(node.description)
}
else {
DisclosureGroup(
isExpanded: $isExpanded,
content: {
if isExpanded {
ForEach(node.children) {
childNode in
OutlineView(node: childNode,
isExpanded: isExpanded)
}
}
},
label: { Text(node.description) })
}
}
}
struct OutlineNode: Identifiable
{
let id = UUID()
var name: String
var children: [OutlineNode]
var description: String {
let localName = NSLocalizedString(name.capitalized, tableName: "OutlineView", comment: "")
return children.isEmpty ? String(format:"📄 %@", localName) : String(format:"📁 %@", localName)
}
init(_ name: String,
_ children: [OutlineNode] = []) {
self.name = name
self.children = children
}
static func newOutline() -> OutlineNode
{
return OutlineNode("root", [OutlineNode("branch1", [OutlineNode ("leaf1"),
OutlineNode("leaf2")]),
OutlineNode("branch2", [OutlineNode ("leaf3"),
OutlineNode("leaf4")])])
}
}