You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS SwiftUI中Table的Context Menu按钮始终禁用求解决方案

macOS SwiftUI Table 右键菜单按钮禁用问题解决
  • 将右键菜单绑定到 TableRow 而非整个 Table
    直接给整个 Table 添加 contextMenu 时,SwiftUI 可能因事件传递层级或 Table 选择状态的逻辑限制,导致菜单按钮被禁用。正确的做法是将右键菜单附加到每一行的 TableRow 组件上:

    ForEach(jiraFilterViewModel.filter) { filter in
        TableRow(filter)
            .contextMenu {
                Label("Do something", image: "house")
            }
    }
    
  • 确认 Selection 绑定的正确性
    如果菜单需要基于选中项执行操作,确保 selection 变量的类型与数据模型匹配(比如模型遵循 Identifiable 协议时,使用 Set<Filter.ID> 或 Filter.ID? 作为绑定类型)。即便手动设置 .disabled(false),空选择状态仍可能导致 Table 级别的菜单处于禁用状态。

  • 移除冗余的禁用状态设置
    你代码中给 Table 添加的 .disabled(false) 属于冗余设置,视图默认处于启用状态,移除后可避免潜在的状态冲突。

修改后的完整代码片段:

@ViewBuilder
func TableView() -> some View {
    VStack(alignment: .trailing) {
        Table(selection: $selection) {
            TableColumn("Name") {
                Text($0.name)
            }.width(300)
            
            TableColumn("Filter ID") {
                Text("\($0.id)")
            }.width(50)
        } rows: {
            ForEach(jiraFilterViewModel.filter) { filter in
                TableRow(filter)
                    .contextMenu {
                        Label("Do something", image: "house")
                    }
            }
        }
        .tableStyle(.inset(alternatesRowBackgrounds: true))
        .onAppear {
            Task {
                do {
                    try await jiraFilterViewModel.populate()
                } catch {
                    print("\(error.localizedDescription)")
                }
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者user753654

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:27:29