gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:26:31 27 4
gpt4 key购买 nike

我有一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com