SwiftUI - 如何使用 DisclosureGroup 正确支持大纲视图中的选择?

问题描述 投票:0回答:0

我正在使用 DisclosureGroups 以大纲形式显示层次结构,并添加代码以使行可选择。这有效,除了无法选择根条目。根线和支线可以按预期展开,可以选择除根线以外的所有线

我正在将其开发为 MacOS 应用程序,但在 iPhone 模拟器中运行它显示了另一个奇怪的行为。单击“根”行(行内的任何位置)时,将切换其公开状态。单击其他行时,只有它们的显示三角形会改变它们的显示状态。

import SwiftUI

@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")])])
    }
}
macos swiftui selection disclosuregroup
© www.soinside.com 2019 - 2024. All rights reserved.