能否为DynamicViewContent编写含@Environment的ViewModifier?
问题:针对DynamicViewContent实现带index参数的DropDestination Modifier是否可行?
我希望实现如下代码的功能:
struct HandleUrlDropModifier<Content>: ViewModifier where Content: DynamicViewContent { @Environment(\.modelContext) var modelContext var content: Content func body(content: Content) -> some View { content .dropDestination(for: URL.self) { items, index in // index 是 Int 类型 handleUrlDrop(items, at: index) } } func handleUrlDrop(_ items: [URL], at index: Int) { modelContext.insert(...) } }
请问这样的实现是否可行?
已尝试的方案
- 直接编写DynamicViewContent的扩展无法实现,因为扩展中不能使用@Environment变量:
extension DynamicViewContent { @Environment(\.modelContext) var modelContext // <- 这里不允许 func handleUrlDrop() -> some View { self .dropDestination(for: URL.self) { items, index in modelContext.insert(...) } } }
- 针对普通View的Modifier可以正常工作,但DynamicViewContent的
.dropDestination的action参数和普通View不同(前者是Int类型的index,后者是CGPoint类型的location):
struct HandleUrlDropModifier: ViewModifier { @Environment(\.modelContext) var modelContext func body(content: Content) -> some View { content .dropDestination(for: URL.self) { items, location in // location 是 CGPoint 类型 handleUrlDrop(items) return true } } func handleUrlDrop(_ items: [URL]) { modelContext.insert(...) } }
内容的提问来源于stack exchange,提问作者fer0n
相关产品推荐
相关产品推荐

