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

SwiftUI:List内嵌LazyVGrid时onDrag拖拽行为失效问题

解决List嵌套LazyVGrid时onDrag被外层劫持的问题

这个问题的核心是SwiftUI的Section默认拥有更高的拖拽交互优先级,会直接覆盖内部元素的onDrag行为,导致拖拽时触发的是整个Section而非单个Grid元素。

最直接的解决方案

给包含LazyVGrid的那个Section添加.listRowDraggable(false)修饰符,显式禁用该Section的拖拽响应,让内部元素的拖拽手势正常生效:

修改后的完整代码:

List {
    Section {
        Text("Some section")
    }
    
    Section {
        LazyVGrid(columns: columns, spacing: 32) {
            ForEach(items) { item in
                Text("\(item.id.hashValue)")
                    .frame(width: 50, height: 50)
                    .background(Color.green)
                    .onDrag {
                        self.dragging = item
                        return NSItemProvider(object: "\(item.id)" as NSString)
                    }
            }
        }
    }
    .listRowDraggable(false) // 关键:禁用当前Section的拖拽能力
}

备选方案(全局禁用)

如果你的整个List都不需要支持拖拽排序功能,也可以通过环境变量强制关闭编辑模式,从根源上避免外层拖拽干扰:

List {
    // 原有内容不变
}
.environment(\.editMode, .constant(.inactive))

不过更推荐第一种方案,因为它精准针对有问题的Section,不会影响其他Section的正常交互。

内容的提问来源于stack exchange,提问作者Kevin R

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:49:59