【问题标题】:macOS SwiftUI Table with contextMenu带有 contextMenu 的 macOS SwiftUI 表
【发布时间】:2022-06-10 21:51:55
【问题描述】:

使用 SwiftUI 的新 Table 容器,如何添加在 Control-click 一行时出现的上下文菜单?

我可以将contextMenu 修饰符添加到TableColumn 的内容中,但是我必须将它添加到每个单独的列中。而且它只适用于特定文本上方,而不适用于整行:

我尝试将修饰符添加到TableColumn 本身,但它显示编译错误:

Value of type 'TableColumn<RowValue, Never, Text, Text>' has no member 'contextMenu'

这是我在源代码方面的内容,TableColumn 的内容中有 contextMenu 修饰符:

struct ContentView: View {

    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: true)])
    private var items: FetchedResults<Item>

    @State
    private var sortOrder = [KeyPathComparator(\Item.name)]

    @State
    private var selection = Set<Item.ID>()

    var body: some View {
        NavigationView {
            Table(items, selection: $selection, sortOrder: $items.sortDescriptors) {
                TableColumn("Column 1") {
                    Text("Item at \($0.name!)")
                        .contextMenu {
                            Button(action: {}) { Text("Action 1") }
                            Divider()
                            Button(action: {}) { Text("Action 2") }
                            Button(action: {}) { Text("Action 3") }
                        }
                }

                TableColumn("Column 2") {
                    Text($0.id.debugDescription)
                }
            }
            .toolbar {
                ToolbarItem {
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }

            if selection.isEmpty {
                Text("Select an item")
            } else if selection.count == 1 {
                Text("Selected \(items.first(where: { $0.id == selection.first! })!.id.debugDescription)")
            } else {
                Text("Selected \(selection.count)")
            }
        }
    }
}

那么,如何将上下文菜单添加到表格内的整行?

【问题讨论】:

    标签: macos swiftui


    【解决方案1】:

    您可以使用以下扩展名制作单元格视图并将其用于每个列单元格,然后它将在任何行位置都可以点击

    Text("Item at \($0.name!)")
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) // << this !!
        .contentShape(Rectangle())                                            // << this !!
        .contextMenu {
            Button(action: {}) { Text("Action 1") }
            Divider()
            Button(action: {}) { Text("Action 2") }
            Button(action: {}) { Text("Action 3") }
        }
    

    backup

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2020-08-05
      • 1970-01-01
      • 2020-11-07
      • 2021-10-10
      • 2021-06-20
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多