macOS 上的 SwiftUI:如何为 onDelete 启用 UI(从列表中删除)

sas*_*sas 7 macos swiftui

也许我今天早上特别密集,但我试图从ListmacOS 上的 SwiftUI 中的a中删除一行。

问题是没有公开用于执行删除的 UI。我的意思是List它不响应删除按键,没有右键单击菜单,也不支持任何其他手势,例如滑动删除(无论如何在 macOS 上会很奇怪)。

这是我正在使用的示例:

import SwiftUI

struct ContentView: View {
    @State var items = ["foo", "bar", "baz"]
    @State var selection: String? = nil

    var body: some View {
        List(selection: $selection) {
            ForEach(items, id: \.self) { Text($0) }
                .onDelete { self.items.remove(atOffsets: $0)}
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}
Run Code Online (Sandbox Code Playgroud)

iOS 上完全相同的代码为我提供了一个带有标准“向左滑动以删除”UI 的表格视图。在 macOS 上什么都没有。

我尝试添加

    .onDeleteCommand(perform: {
        if let sel = self.selection, let idx = self.items.firstIndex(of: sel) {
            self.items.remove(at: idx)
        }
    })
Run Code Online (Sandbox Code Playgroud)

List但仍然没有响应删除按键。

如何List在 macOS 上启用行删除?

kpr*_*ter 16

对于 macOS,我们使用右键单击并查看“删除”等菜单选项。您可以将上下文菜单添加到列表中,例如

  List(selection: $selection) {
        ForEach(items, id: \.self) { item in
               Text(item) 
                   .contextMenu {
                       Button(action: { 
                       // delete item in items array 
                       }){
                       Text("Delete")
                       }
                    }
        }
            
  }
Run Code Online (Sandbox Code Playgroud)


ggr*_*uen 7

此代码启用“删除”菜单并在我选择“编辑”>“删除”时删除所选项目(无需手动连接菜单):

struct ContentView: View {
    @State var items = ["foo", "bar", "baz"]
    @State var selection: String? = nil

    var body: some View {
        List(selection: $selection) {
            ForEach(items, id: \.self) { Text($0) }
        }
        .onDeleteCommand {
            if
                let sel = self.selection,
                let idx = self.items.firstIndex(of: sel) {
                print("delete item: \(sel)")
                self.items.remove(at: idx)
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .animation(.default)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,要使删除起作用,请使其成为删除菜单选项的等效键盘: - 编辑 Main.storyboard - 选择编辑 > 删除 - 单击“等效键”字段 - 按下删除键。

在此处输入图片说明

运行应用程序,选择一个项目,点击删除键,你的项目应该消失了。


sas*_*sas 1

我已经找到了一个相当复杂的解决方案,我希望有更好的方法。

我所做的如下:

  • 将操作连接到现有的“删除”命令
  • 创建一个“ObservableObject”Menu来发布选定的菜单命令
  • 将发布者传递给 ,ContentView以便它可以订阅并对更改采取行动

这是两个相关文件:

第一的,AppDelegate.swift

enum MenuCommand {
    case none
    case delete
}

class Menu: ObservableObject {
    @Published var item: MenuCommand = .none
}


@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var window: NSWindow!
    @ObservedObject var menu = Menu()

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView(menu: menu)

        // Create the window and set the content view. 
        window = NSWindow(
            contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered, defer: false)
        window.center()
        window.setFrameAutosaveName("Main Window")
        window.contentView = NSHostingView(rootView: contentView)
        window.makeKeyAndOrderFront(nil)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    @IBAction func delete(_ sender: Any) {
        print("delete menu")
        menu.item = .delete
    }

}
Run Code Online (Sandbox Code Playgroud)

ContentView.swift

import SwiftUI

struct ContentView: View {
    @ObservedObject var menu: Menu
    @State var items = ["foo", "bar", "baz"]
    @State var selection: String? = nil

    var body: some View {
        List(selection: $selection) {
            ForEach(items, id: \.self) { Text($0) }
        }
        .onReceive(
            self.menu.objectWillChange
                .receive(on: RunLoop.main)) { _ in
            if
                case .delete = self.menu.item,
                let sel = self.selection,
                let idx = self.items.firstIndex(of: sel) {
                print("delete item: \(sel)")
                self.items.remove(at: idx)
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .animation(.default)
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:不要忘记将“删除”菜单项连接到IBAction.