【问题标题】:How to get the drop target background effect in sidebars on macOS using SwiftUI?如何使用 SwiftUI 在 macOS 的侧边栏中获得放置目标背景效果?
【发布时间】:2022-10-14 19:43:21
【问题描述】:

我有一个 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 中的一个示例:

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

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

但这看起来不太一样:

有趣的是,如果您使用侧边栏列表的选择,我想要的效果是一样的:List(selection: $selectedItem)

必须有一种本地方式来做到这一点,这样我就不必伪造它并得到看起来不太正确的东西。

【问题讨论】:

  • "但这看起来不太一样“,你是说矩形吗?
  • 是的。我想要与第一个屏幕截图相同的样式。使用大量自定义代码,它可能会起作用,但是由于您在其他地方免费获得它,因此可能有一种简单的方法可以将其用于放置目的地。

标签: macos swiftui drag-and-drop sidebar


【解决方案1】:

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
                            }
                        }
                    }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2017-01-07
    相关资源
    最近更新 更多