You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 22:07:07