macos - 如何使用 SwiftUI 在 macOS 侧边栏中获得放置目标背景效果?

标签 macos swiftui drag-and-drop sidebar

我有一个 SwiftUI 列表,它是 macOS 上的侧边栏。对于它的项目,我添加了 dropDesternation像这样的修饰符:

.dropDestination(for: URL.self) { urls, _ in
      for url in urls {
          //... adding urls to destination
      }
}

return true
} isTargeted: { inDropArea in
      if inDropArea {
          highlightedItem = item
      } else {
          highlightedItem = nil
    }
}
       

默认情况下,如果光标在项目上方,我不会有任何效果,但我想要与在 AppKit 中使用 NSOutlineView 相同的效果。这是 Finder 中的示例:

Drag and drop in the Finder sidebar

如您所见,我在上面的代码中实现了highlightedItem。我可以用它来检查某个项目是否被定位并绘制背景:

 .background {
       if item == highlightedItem {
            RoundedRectangle(cornerRadius: 5)
            .fill(Color.blue)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
       }
}

但这看起来不太一样:

own implementation of sidebar drop target

有趣的是,如果您对侧边栏列表使用选择,我想要的效果与您获得的效果相同:List(selection: $selectedItem)

必须有一种 native 方法来执行此操作,这样我就不必伪造它并得到看起来不太正确的东西。

最佳答案

List 元素可选择并暂时触发该选择似乎工作得很好。

例如……

let Bands: Array<String> = [
    "Beatles", "Rolling Stones", "Animals", "Beach Boys", "Doors",
]

struct ContentView: View {
    @State var selection: String? = nil
    @State var dropSelectionCache: String? = nil

    var body: some View {
        VStack {
            Text("Drag text on onto band to trigger highlighting")
            List(Bands, id: \.self, selection: $selection) { band in
                Text(band)
                    .dropDestination(for: String.self) { _, _ in
                        true
                    } isTargeted: { (isTarget: Bool) in
                        if isTarget {
                            dropSelectionCache = selection
                            withAnimation {
                                selection = band
                            }
                        } else {
                            withAnimation {
                                selection = dropSelectionCache
                            }
                        }
                    }
            }
        }
    }
}

这是一个 gif,展示了在 Ventura 上运行的代码(抱歉屏幕录制有点不稳定 - 那是我,而不是代码 :-/)

Low res drag and drop showing code in operation

关于macos - 如何使用 SwiftUI 在 macOS 侧边栏中获得放置目标背景效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73743903/

相关文章:

c++ - 如何在 Qt 应用程序中获取 MAC 操作系统中驱动器的文件格式?

HTML5 视频未在 Mac OS X(桌面)CNA(强制网络助手)上显示

macos - "Invalid development certificate found"在 Mac 上

swift - 如何在 `User_Mention`中按 `SearchBar`进行过滤

java - 添加 JComponent 后 getY() 返回 0

c# - WPF将窗口拖动到桌面

c - Travis CI 使用非 perl 语言安装 perl 模块

swift - SwiftUI 分段选择器的问题

swift - macOS 上的 NavigationLink 未在同一 View 中打开

android - DragEventListener 不适用于三星 S7 (6.0)